diff --git a/AGENTS.md b/AGENTS.md index f734e28..564b3c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,10 @@ engine binaries. Keep managed engines separate from a user's global CLI setup. Personal projects stay local. Opt-in Team Sync may share planning, comments, activity and explicitly published results; source changes use Git in this preview. Cloud models may be used by an explicitly selected installed harness. +- On a shared project (MemSync), a worker's conversation is its person's alone, on + each of their computers. Everyone else gets the request, how the run stands, a + summary of each round of work, its review, what it changed and the documents and + images its worker made. Only the worker's own account continues it. - Do not invent live workers, successful tests, metric values or confidence. The example project must remain visibly labelled as example data. - A worker exit creates a review candidate, never an automatically verified change. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5e50b9d..da4ccbf 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -795,10 +795,12 @@ commit and provenance in the inventory. | npm | is-promise | 4.0.0 | MIT | [Source](https://www.npmjs.com/package/is-promise/v/4.0.0) | | npm | isarray | 1.0.0 | MIT | [Source](https://www.npmjs.com/package/isarray/v/1.0.0) | | npm | isexe | 2.0.0 | ISC | [Source](https://www.npmjs.com/package/isexe/v/2.0.0) | +| npm | isomorphic.js | 0.2.5 | MIT | [Source](https://www.npmjs.com/package/isomorphic.js/v/0.2.5) | | npm | jose | 6.2.17 | MIT | [Source](https://www.npmjs.com/package/jose/v/6.2.17) | | npm | json-schema-traverse | 1.0.0 | MIT | [Source](https://www.npmjs.com/package/json-schema-traverse/v/1.0.0) | | npm | json-schema-typed | 8.0.2 | BSD-2-Clause | [Source](https://www.npmjs.com/package/json-schema-typed/v/8.0.2) | | npm | jszip | 3.10.2 | (MIT OR GPL-3.0-or-later) | [Source](https://www.npmjs.com/package/jszip/v/3.10.2) | +| npm | lib0 | 0.2.120 | MIT | [Source](https://www.npmjs.com/package/lib0/v/0.2.120) | | npm | lie | 3.3.0 | MIT | [Source](https://www.npmjs.com/package/lie/v/3.3.0) | | npm | longest-streak | 3.1.0 | MIT | [Source](https://www.npmjs.com/package/longest-streak/v/3.1.0) | | npm | lucide-react | 1.72.0 | ISC | [Source](https://www.npmjs.com/package/lucide-react/v/1.72.0) | @@ -932,6 +934,7 @@ commit and provenance in the inventory. | npm | which | 2.0.2 | ISC | [Source](https://www.npmjs.com/package/which/v/2.0.2) | | npm | worker-f | 0.1.24 | MIT | [Source](https://www.npmjs.com/package/worker-f/v/0.1.24) | | npm | wrappy | 1.0.2 | ISC | [Source](https://www.npmjs.com/package/wrappy/v/1.0.2) | +| npm | yjs | 13.6.33 | MIT | [Source](https://www.npmjs.com/package/yjs/v/13.6.33) | | npm | zod-to-json-schema | 3.25.2 | ISC | [Source](https://www.npmjs.com/package/zod-to-json-schema/v/3.25.2) | | npm | zod | 4.6.7 | MIT | [Source](https://www.npmjs.com/package/zod/v/4.6.7) | | npm | zrender | 6.1.0 | BSD-3-Clause | [Source](https://www.npmjs.com/package/zrender/v/6.1.0) | diff --git a/docs/account-and-workers.md b/docs/account-and-workers.md index 69e872c..a849340 100644 --- a/docs/account-and-workers.md +++ b/docs/account-and-workers.md @@ -134,3 +134,41 @@ are omitted and Memtrace sign-in opens only the official claim host. Actual installed status checks on the Windows development machine confirmed the Codex, Claude Code and Cursor CLIs had existing provider authentication, without granting production consent. + +### DeepSeek Harness setup and ACP profiles + +When DeepSeek Harness (`dsh`) is not on `PATH` and DeepSeek Harness Desktop is +installed, **Workers** detects the Desktop app and runs its bundled +`command-manager.js` helper with the Desktop app’s bundled Node runtime and a +verified inspect fingerprint. On Windows, MemCode refreshes the user `PATH` +in-process after installation; on macOS, if `/usr/local/bin/dsh` returns +`EACCES` or `EPERM`, MemCode directs the user to **Manage dsh Command…** in +DeepSeek Harness Desktop without invoking `osascript`. + +MemCode scans `$DSH_HOME/profiles/*` for ACP profiles (`@deepseek-ai/dsh-acp-app` +or `@deepseek-ai/dsh-acp`), excluding conflicting web/Desktop bundles, +`node_modules`, and temporary `memcode-dryrun-*` directories. When +`settings.dshProfile` is unset, MemCode automatically selects a customized ACP +profile if present; when no ACP profile exists (or only non-ACP profiles are +found), setup guides the user through creating one before connecting. + +Desktop-to-ACP provider sync compares Desktop `llm-pi-ai` entries in +`cordis.patch.yml` and `@deepseek-ai/dsh-llm` `registerAdapter` plugins against +the active ACP profile. Inline credentials and unsafe YAML tags are skipped, +and `link:`/`file:` local plugins stay unchecked by default; a relative local +path is resolved against the Desktop profile. When `$DSH_HOME/cordis.patch.yml` +sets `llm-pi-ai`, it replaces every profile's providers, so custom providers are +not offered for import into a profile and the list says why. + +Selected providers are tested first in an isolated `memcode-dryrun-*` staging +profile that gets its own copy of the target's dependency tree. The unchanged +profile is checked first; then each provider must actually contribute models to +the strict ACP catalog. Failing providers are isolated with a **Retry without +broken providers** action before the target profile is modified. **Import** +applies only the plan that dry-run verified and refuses if Desktop, the home +patch or the target changed in between. A failed import restores the profile +files, reinstalls the restored lockfile and reports whether rollback completed. +DeepSeek Harness reviews, plans and workers do not start while setup changes the +profile, and setup waits for running dsh reviews; quitting MemCode waits for an +import to finish. ACP model catalogs preserve provider group headings and full +`["provider", "model"]` identifiers in Worker Assignment. diff --git a/docs/macos-development.md b/docs/macos-development.md index 444283d..aa9ccf7 100644 --- a/docs/macos-development.md +++ b/docs/macos-development.md @@ -46,14 +46,14 @@ Install and sign in to at least one supported coding CLI using that provider's o You can inspect the board and participate in planning before connecting a worker. -## Join a team +## Open a shared project -1. Open **Team**. If your team is listed, select the shared project under **Team projects**. -2. Otherwise, ask a teammate to open that project on their computer and choose **Team → Invite teammate**. On your Mac, open the project selector, choose **Join a team project**, paste the invitation and select **Continue**. Check the team and project names, choose **Accept and open**, and approve the intended Memtrace account if prompted. -3. Check **Team** for the planning sync status. Open **Cycles** to see current and completed cycles. Look in **Workspace → Done** for completed stories and clear any board filters that hide them. -4. When you want to run a worker, choose **Work on this computer** and connect your existing checkout or clone the repository. Team sync carries the board and shared results. Git carries source changes. +1. Open the project selector. A project shared with you, or shared from another of your own computers, is listed there: choose **Join** for an invitation, or **Open** for your own. +2. To share a project yourself, open it and choose **Share** at the top right, then invite people by email. +3. Open **Cycles** to see current and completed cycles. Look in **Workspace → Done** for completed stories and clear any board filters that hide them. +4. When you want to run a worker, connect your existing checkout or clone the repository. Sharing carries the board, summaries, changes and the files you share. Git carries source changes. -See [the Team Sync guide](team-sync-preview.md) for hosting and sharing boundaries. +See [shared projects](shared-projects.md). The **Team** page is only shown for a project still in a Team Sync team, so it can be left; see [the Team Sync guide](team-sync-preview.md). ## Find the product tour and review guide diff --git a/docs/shared-board-layout-proposal.md b/docs/shared-board-layout-proposal.md new file mode 100644 index 0000000..0cf77c7 --- /dev/null +++ b/docs/shared-board-layout-proposal.md @@ -0,0 +1,428 @@ +# The board as one Yjs document + +Status: accepted. Alex approved this layout on 21 November 2026 and asked for board sync +to be built on it. It is built on the branch `feat/memsync-shared-projects`, and +[Shared projects](shared-projects.md) says how it runs. Nothing is deployed. + +MemSync keeps a board as a log of Yjs updates and never looks inside one +(its ADR-0004 and ADR-0013). What is inside is MemCode's to define. This page says what +that layout is, how a board that already exists on a computer becomes the first updates, +and what MemCode does with an update it cannot apply. + +It was written as a proposal and is kept as the record of what was decided. Where +building it showed the proposal wrong, or where Alex decided otherwise, the text says so +under **As built** or **Corrected**. What is still missing is listed under +[Not built](#not-built). + +## What a board holds today + +Team Sync already draws the line between what is shared and what stays on a computer, in +`runtime/team/projection.ts` and `runtime/team/history.ts`. The proposal keeps that line. + +| On the board | Not on the board | +| --- | --- | +| Goals: identifier, title, description, phase, color, order, branch, base revision | Worker conversations and tool output | +| Cycles: name, goal, dates, time zone, state, capacity, calendar | The worker, model, route and permissions of a task | +| Tasks: identifier, title, description, stage, lane, priority, kind, goal, cycle, parent, estimate, dates, labels, scope, what it depends on, related tasks, runbook, custom fields, archived | Run state, changes, measurements, review runs | +| Comments on tasks, with their replies | Local paths, the checkout, credentials | +| Lanes, custom field definitions and saved views of the project | Insights from code analysis | + +Claims, messages to a worker, conversations and published results are not board data. +MemSync's ADR-0005 gives them their own calls, and none of them is in this document. + +**Corrected.** The right-hand column was first headed "Stays on the computer", as if that +were the product. It is not. Alex's rule of 21 November 2026: someone on a project who +opens a card sees its conversation, how it was solved, its artifacts and changes and who +did it, as it happens. Only running the worker stays on the computer it runs on. None of +that belongs in the board document, and MemSync does not carry it yet: its ADR-0005, a log +for each conversation and calls for claims and messages, is accepted and not built. Until +it is, a card that arrives on another computer has its brief, its runbook and its +comments, and not its conversation, artifacts or changes. + +## The document + +One Yjs document per shared project. Every collection is a map at the top of the document, +named once and never created at run time. An entry is a map of fields under the id of the +thing it describes. + +``` +goals id → { identifier, title, description, phase, color, order, branch, baseRevision, baseBranch, closed, deleted } +cycles id → { name, goal, startDate, endDate, timeZone, state, capacity, calendar, deleted } +tasks id → { identifier, title, description, stage, lane, priority, kind, goal, cycle, parent, + estimate, startDate, dueDate, duplicateOf, category, archived, deleted, + label:, scope:, depends:, related:, + field:, step: } +comments id → { task, parent, text, reference, deleted } +lanes id → { name, stage, color, order, wipLimit, deleted } +fields id → { name, type, options, deleted } +views id → { name, mode, groupBy, sortBy, filters, deleted } +meta { layout: 1 } +``` + +`description` on a goal and on a task is a Yjs text. Every other value is plain: text, a +number, true or false, nothing, or a small object that is always replaced as a whole. + +### Why it is shaped this way + +- **Collections at the top, entries by id.** Two computers that add different tasks never + touch the same key, and two that edit different fields of one task both keep their edit. + Two that set the same field at the same moment end with one of the two values, the same + one everywhere. +- **An entry is made once.** When two computers each put a new map under the same id, one + whole map replaces the other and edits to the loser are gone. Measured with Yjs 13.6.33: + an entry made as "from A" and then edited on A read "from B" on both computers after + they met. So MemCode writes fields into an entry that is already there and makes a new + entry only for an id the document has never held. +- **A set is one key per member.** `label:urgent`, `depends:` and `step:` + are keys of the task's own entry. Adding a label on one computer and another label on a + second keeps both, where a list stored as one value would keep one computer's list. + A step of the runbook holds `{ text, done, order }`, so a worker ticking one step and a + person rewording another do not undo each other. +- **Descriptions merge.** A description is long and two people do edit one at once. As a + Yjs text, MemCode writes the difference between the old and the new wording, and edits + in different places both stay. Titles and comment texts are replaced whole. +- **Stage and lane are written together.** A task has both today. Each move writes both + in one step. Two computers moving the same task at once then end with one computer's + pair, never a stage from one and a lane from the other: 200 rounds, no mixed pair. +- **Deleting marks, it does not remove.** `deleted: true` hides the entry. Removing the + key would throw away an edit made at the same moment on another computer, and would + leave nothing to restore. A marked entry is small and stays in the document. + +### Order + +- **Tasks have no order of their own.** A column is sorted by the view: priority, updated, + created, due or estimate. Nothing is stored. If cards are ever ordered by hand, a task + gets a `rank` field then, and the layout number stays 1. +- **Goals keep the `order` number they are given when they are made.** They cannot be + reordered today. +- **Lanes keep `order` as their position.** Reordering lanes writes the position of every + lane in one step, as it does today. Two computers reordering at once end with one + computer's order, whole. Two lanes with the same number are shown by id, so every + computer shows the same order. + +### Ids + +Ids in the document are the ids the first computer already uses for its goals, cycles, +tasks and comments. They are UUIDs, so a second computer takes them as its own. + +Lane ids are the exception: today they begin with the local project's id +(`:backlog`). In the document they are written without it (`backlog`, +`planned`), and each computer puts its own project id back in front. Team Sync does the +same translation today. + +### Identifiers such as MC-014 + +Two computers that are offline can both create MC-014. Nobody numbers tasks for them, +because MemSync does not read the board. + +The rule: the log decides. Every computer applies the log in the same order, so every +computer sees the same task arrive first with a given identifier. A task that arrives with +an identifier already taken gets the number after the highest one in use, and that new +identifier is written to the document as an ordinary change. Every computer works +out the same number from the same log, so it does not matter which of them writes it. + +Existing identifiers never change when a board is first shared. + +**As built.** A task arrives with the log entry that made it, and MemCode keeps that +number for every task. A task that is not in the log yet gives way to one that is. Two +that arrived in the same entry are told apart by id. The rule is in +`runtime/sharing/board/identifiers.ts`. + +### Who and when + +A Yjs update carries no time and no author that can be trusted. MemSync stamps both on +every update: `logged_at` and `author_account_id`. + +- A task, goal, cycle or comment was **created** when the update that first held it was + logged, and **changed** when the last update that touched it was logged. +- A comment's **author** is the account that logged its first update. A change to a + comment logged by anyone else is not shown. +- The **delivery history** (when a task changed stage, cycle or estimate, which is what + burn-down is drawn from) is read off the same way, update by update, so every computer + draws the same chart. Cycle baselines and snapshots are worked out, not stored. +- A change that has not reached the log yet is shown with the computer's own clock until + its receipt arrives. + +Nothing in the document says who wrote it or when. + +**As built.** What arrives from the log is dated and signed this way: when a task, cycle +or comment was made and last changed, and who wrote a comment. Three parts of this +section are not built. A change made on this computer keeps this computer's clock, also +after the log has dated it. A change to someone else's comment is shown like any other. +The delivery history is still each computer's own. + +### Not trusting what is read + +Anyone on the project can add an update, and an update can hold anything. MemCode checks +each value as it reads it, with the limits Team Sync has today (a title of at most 240 +characters, a text of at most 20,000, and so on). A value that does not pass is left out +and the last good value stays on screen. A field MemCode does not know is kept and +ignored, which is how a newer MemCode can add one. + +`meta.layout` is 1. A MemCode that finds a higher number shows the board without writing +to it and asks to be updated. + +## On each computer + +The board the app shows stays what it is today: the workspace file. Beside it, for each +connected project, MemCode keeps: + +- the document as the log has built it so far, +- the number of the last log entry it has dealt with, +- its own changes that are not in the log yet, each with the id it will be sent under, +- the log entries it could not apply. + +**As built.** These are two files in a folder of their own under `shared-boards/` in the +profile: `log.bin` is the document, `sync.json` is the rest, with the board as this +computer last wrote or took it. Changes made here are found by comparing the workspace +with that board. A change that comes from the log is saved together with the workspace +file. The save is written beside what is there, then the workspace file is written, then +the save is put in place. Both carry the same counter, so after a crash MemCode can tell +whether the workspace got there, and finishes the save or drops it. + +A local change becomes a Yjs update against the document and joins the unsent changes. +An update from the log is applied to the document and then copied into the workspace +file, field by field. Workers, conversations and everything else in the right-hand column +of the first table never pass through the document. + +Reading follows MemSync's runtime view: `ReadUpdates` in pages until a page is empty, then +`WatchUpdates` from the last number, and again from that number when the stream ends. + +## A board that already exists + +The first computer to connect a board with content to a shared project whose log is empty +writes the board into the log. + +1. Read the log. If it is not empty, see "Two boards meet" below. +2. Build the updates: `meta` first, then lanes, fields and views, then cycles, goals, tasks + and comments. One entry is one update. +3. Write every update to disk with a new id before sending any. +4. Send them in calls of at most 100 updates and at most 3 MiB together, in order. + MemSync takes 4 MiB a call unless it is set up otherwise. +5. A call whose answer is lost is sent again as it was. MemSync adds nothing twice, + because the ids are the same. + +Step 3 is what makes this safe to interrupt. If the updates were built again after a crash +they would be different bytes with different ids, and every entry would be made twice. + +Measured with Yjs 13.6.33: a task with a 600-character description is an update of 953 +bytes, and one with the longest description allowed today, 20,000 characters, is 20,366 +bytes. A board of 2,000 tasks is 2,000 updates and 1.95 MB, which is 20 calls. + +No update comes near 1 MiB unless one value is that large by itself. MemCode splits a +change that would exceed 1 MiB into several updates: the entry first, then a long text in +pieces. A single value over 1 MiB cannot be split. MemCode refuses to save it, with the +sentence for `update_too_large`. + +**As built.** A change is written in pieces of about 256 KiB. An entry stays whole when +it fits in one, and an entry that is larger goes key by key. A single value of about +1 MiB or more is not written to the board. It stays on the computer it was typed on, and +the Share panel says so. MemCode does not refuse to save it. + +### Two boards meet + +The second computer finds a log that already has a board. If its own local project is +empty, it takes the board from the log. That is the case of a second computer. + +If both have content, the proposal is to keep everything: the entries of the local board +are added to the log as new entries. Ids cannot collide, and identifiers that do are +renumbered by the rule above. Nothing is lost and nothing is merged by guesswork. The +person is told how many tasks will be added before it happens. + +**Corrected: nothing is merged.** Alex decided otherwise on 21 November 2026: "you either +share your own project, or you join someone else's and get their board. Nothing is ever +merged. That is as simple as that." So: + +- Sharing your own project puts your board into a shared project whose log has no work + in it. +- Joining, whether someone else's project or your own from another computer, gives you + the board that is in the log. The joining computer adds nothing of its own, not a lane + and not a custom field. +- A project that already has work is never merged into a board that already exists. + Connecting answers with one sentence, and the project is not connected: "app already + has work of its own, so it cannot join Website: connect a project that has none yet." + +A first version of the code did keep both, behind a question. It was taken out again. + +The same board on two computers of one person, with the same ids, is not two boards: the +second computer finds its ids in the document and adds only what is missing. + +Two computers that both find the log empty at the same moment will both write. MemSync +has no way to say "add this only if the log is still empty". For one board on two +computers that means entries made twice under the same id, which is the case measured +above where one whole entry wins. It needs both computers to connect for the first time +within the same seconds. A small addition to MemSync would close it; see below. + +## An update that cannot be applied + +MemSync cannot tell a damaged update from a good one, so every computer may be handed one. +The rule is MemSync's: skip it and say so, never stop syncing. + +What the Yjs library does, measured with version 13.6.33 on a small document: + +| What was done to a real update | Tries | Refused | Applied as if real | Left waiting | +| --- | --- | --- | --- | --- | +| Cut short at every length | 677 | 677 | 0 | 0 | +| One byte inverted, at every position | 677 | 677 | 0 | 0 | +| One bit flipped, at every position | 5,416 | 1,007 | 4,051 | 358 | +| Random bytes | 5,000 | 5,000 | 0 | 0 | +| Counts that promise far more than the bytes hold | 4 | 4 | 0 | 0 | + +No try took longer than 40 milliseconds, and none grew the memory in use. + +Three things follow. + +**A refused update can still change the document.** In 48 of the tries above, applying +threw an error and the document was no longer what it had been. Applying is not all or +nothing. In all 48, reading the update without applying it (`decodeUpdate`) had already +failed. So: + +1. An update larger than 1 MiB, or one that `decodeUpdate` refuses, is never applied. +2. An update is applied to the document inside a guard. If applying throws anyway, the + document in memory is dropped and loaded again from disk as it was after the last entry + that applied. +3. Either way the entry is written down as not applied (its number, id, author and time) + and the next entry is read. The number of the last entry dealt with moves on. + +**As built: reading first is not enough.** The proposal said that reading an update had +refused every update that went on to fail. A second measurement, kept as a test, found +otherwise. Of 2,241 damaged copies of two small updates, 839 made `applyUpdate` throw, +and 7 of those had read fine with `decodeUpdate`. So the guard in rule 2 is used, not just +kept in reserve. MemCode then goes back to the documents it last saved, reads the log +again from there and leaves that entry out. + +**Damage that still reads as an update cannot be seen.** Three quarters of the single +flipped bits gave an update that applied: a changed letter, a changed number. MemCode +cannot know. What it can do is give every update an id made from its bytes (a UUID built +from their SHA-256). A reader that finds bytes which do not match their id knows the +update changed after it was written, and treats it as not applied. This catches damage in +storage and on the way. It does not catch a MemCode that writes nonsense on purpose, and +nothing in a board without a server that reads it can. + +**An update can wait for one that never comes.** Yjs applies an update that builds on +something missing by setting it aside. In the measurement, two changes to a task applied +without the update that created it left the task invisible and the document waiting. That +is what happens to everything a person wrote after a damaged update of theirs, on every +other computer. + +The repair is that whoever has more than the log sends it. After catching up, each +computer compares its own document with the one the log builds and sends the difference +as a new update. In the measurement the author's difference was 350 bytes, and the two +waiting changes took effect on arrival. As long as one computer still holds what a damaged +update carried, the board heals. If none does, the waiting updates stay set aside and are +listed with the updates that could not be applied. + +**As built: what waits, and who repairs.** Two things are narrower than the paragraphs +above say. + +What waits is wider than one task. Yjs takes the changes of one writer in order, and a +writer is one run of MemCode on one computer. After a left-out update, everything that +run wrote later is set aside on the computers that left it out, whatever it touches. +MemCode started again is a new writer, and what it writes from then on arrives, unless it +changes something the lost update made. + +The repair is done by one computer only: the one that wrote the update. It sees its own +update come back from the log damaged, and sends what the log lacks as a new update. The +same bytes can be sent under up to eight ids, so the repair is never mistaken for the +entry it repairs. A computer that alone could not read an update, because of a fault on +its own side or because it runs a MemCode that reads updates differently, is not +repaired by anyone: nobody else knows. It shows the line about changes left out, and +"Some changes are set aside until one they build on arrives". Damage that appears in the +log after the author has read the update back is in the same place. + +What the person sees: a line in the Share panel such as "2 changes from Dana Ek on +21 November could not be read and were left out", with nothing else interrupted. + +Two computers with different versions of MemCode could disagree about one update. The one +that left it out will set later changes aside. The proposal said the same repair covers +it. It does not, for the reason above. Updating MemCode on that computer and connecting +the project again does. + +## What this added to MemCode + +- The `yjs` package, 13.6.33 (MIT, three packages with what it needs). It is the first + package added for sharing, and it is in the lock file and the third-party notices. + MemSync's tests use `yrs`, which reads and writes the same v1 updates. +- Two more calls of the kind MemCode already made, and one that stays open + (`WatchUpdates`). The gRPC client learned to read a reply that has many parts. +- The measurements on this page as tests, in `tests/sharing-board-updates.test.ts` and + `tests/sharing-board-document.test.ts`. + +## Not built + +- **A card's conversation for everyone on the project** is no longer missing: it is in a + log of its own per card (MemSync ADR-0014), not in this document. See "What happens on + a card" in [Shared projects](shared-projects.md). +- **A change to someone else's comment is shown.** MemCode itself lets only the author + change a comment. Nothing stops a changed MemCode from writing one, and other computers + would show it. +- **The delivery history is not read off the log.** Burn-down and cycle snapshots stay + each computer's own, drawn from what that computer saw and when. A cycle that a + computer sees start or finish gets the same starting baseline and closing count it + would get if it had been started or finished there. A computer that joins after a cycle + started shows no baseline for it. +- **A change made on this computer keeps this computer's clock.** Other computers date it + by the log. Sorting by "updated" can differ by seconds between computers. +- **Nobody repairs a computer that alone could not read an update.** See above. +- **A value of about 1 MiB or more is not shared.** No field in MemCode accepts one today. +- **A snapshot.** A new computer reads the whole log. +- **Two computers that both find the log empty in the same second both write the board.** + It needs the same board, with the same ids, on both. MemSync has no "only if the log is + still empty". + +## What would help from MemSync + +None of this blocks a first version. + +- **Add only if the log is at a number.** One optional field on `AppendUpdates` closes the + case of two computers writing a first board at once. +- **A snapshot.** The log only grows and a new computer reads all of it. At 2,000 tasks + that is 2 MB. MemSync's own notes already list this. +- **A reader for the delivery history** that is safe on bytes from outside, and that reads + this layout. Until then MemCode works the history out itself, as described above. + +## Decisions + +Alex was asked on 21 November 2026 whether he approved the layout on this page so that +board sync could be built on it, and answered "Yes, build it". The ten points below were +put to him as one question and were not gone through one by one. Point 3 he decided the +other way the same evening. + +1. **Is this the layout?** Collections at the top, an entry per id, one key per member of + a set, descriptions as Yjs text, everything else replaced whole. +2. **Deleting on a shared board marks the entry and keeps it.** Today a deleted task is + gone. The alternative is to remove it, which loses a simultaneous edit and cannot be + undone. +3. **When two boards with content meet, keep everything from both.** The alternatives + were to refuse and make the person choose one, or to let the shared board replace the + local one. **Decided otherwise:** nothing is merged, and the project is not connected. + See "Two boards meet". +4. **Anyone on a project can change anything on its board**, guests included, except + another person's comment. MemSync lets everyone on a project add updates, so a stricter + rule would live in MemCode alone and could be worked around. +5. **A second MC-014 is renumbered by log order.** The alternative is a prefix per person. +6. **Saved views, lanes and custom fields are shared**, as Team Sync shares them. Views + could be each person's own instead. +7. **The runbook is shared**, as it is in Team Sync, so the other computer sees a worker + tick its steps. +8. **Update ids are made from the bytes.** MemSync only asks for a UUID, so this needs no + change there. +9. **Add `yjs` to MemCode.** +10. **A project in Team Sync is not carried over by this.** Moving the two boards that + exist on the relay is a step of its own. + +## Looked at and left out + +- **One list per collection instead of a map by id.** Order would be free, but Yjs has no + move: moving an entry is removing and adding it, and two computers moving the same one + leave it there twice. +- **Everything as one value per task.** Simple, and any two edits to the same task at once + would lose one. +- **Every set as a nested Yjs map.** It merges like one key per member, at the price of + several nested types per task. Each nested type is something two computers can make at + the same moment, with one replacing the other. +- **A collection per task at the top of the document**, so that nothing nested is ever + made at run time. It removes the "made once" rule and leaves thousands of names at the + top that can never be removed. The rule is simpler than that. +- **Checking an update on a server before logging it.** MemSync decided against reading + updates, because the Rust library it would use is not safe on bytes from outside. diff --git a/docs/shared-projects.md b/docs/shared-projects.md new file mode 100644 index 0000000..1da70c7 --- /dev/null +++ b/docs/shared-projects.md @@ -0,0 +1,672 @@ +# Shared projects + +MemCode can share a project through MemSync, the service that is to replace Team Sync: +start it, invite people, and keep its board the same on every computer that has it. This +page says what exists, how MemCode finds the service and how to try it on one computer. + +MemSync runs at `https://sync.hosted.memtrace.io`, and memtrace.io's list of MemCode +services names it. This branch of MemCode uses it; no released MemCode does yet. Sharing +replaces Team Sync: the **Team** page in the sidebar is only shown for a project still in a +Team Sync team, so it can be managed and left, and the project menu no longer offers +**Join a team project**. The in-app guide's "Share a project" topic describes Share. + +## What it does today + +- Signs in to MemSync with the Memtrace account MemCode is already connected to. +- Shares the open project from a **Share** button at the top right of the project. The + first Share or Invite starts a shared project of the same name and writes the board to + it. Nobody is sent to a website, and nothing is set up first. +- Invites people by email, cancels an invitation, and removes a guest, for the owner. + A guest sees who is on the project and can leave it. +- Lists, in the project switcher, the shared projects not on this computer yet and the + invitations waiting for the person. **Open** and **Join** make a project here and give + it the shared board. +- Keeps the board of a connected project in step with the shared project: goals, cycles, + tasks with their runbooks, comments, lanes, custom fields and saved views. See + [Keeping the board in step](#keeping-the-board-in-step). +- Shows what happened on a card to everyone on the project: the request, who runs a worker + on it and how it stands, then the summary of each round of work, what it changed, its + code review and the documents and images its worker made, with who did each. The + conversation is the person's own, on each of their computers. See + [What happens on a card](#what-happens-on-a-card). + +Renaming and deleting a shared project happen at memtrace.io. Deleting it in MemCode's +project switcher removes it from this computer only: the computer disconnects, the others +keep it, and it can be opened again from the switcher. Workers run only on the +computer that started them. Source changes travel through Git. + +A project is the thing people share. There is no team. A person's own computers are never +invited: signing in to MemCode on each is enough, and the project is then in the switcher +on each, ready to open. + +## Where MemCode finds sharing + +MemCode reads `https://www.memtrace.io/api/memcode/services`, the list Team Sync reads too, +and takes sharing from its `sharing` entry: + +```json +{ + "version": 1, + "sharing": { + "endpoint": "https://sync.memtrace.io", + "tokenEndpoint": "https://www.memtrace.io/api/memcode/memsync/token" + } +} +``` + +- No `sharing` entry: sharing is not offered, and there is no Share button. +- The list is asked for without the person's sign-in, at most once a minute. When it + cannot be read, sharing is treated as not offered until the next try, and the reason + goes to the runtime's log on a line that starts with `[sharing]`. +- The two addresses are still checked before use. MemSync's address must be `https://`, + or plain `http://` on this computer, because every call carries an access token. The + token address must be at `https://www.memtrace.io` or on this computer, because the + request carries the session's refresh token and the only session MemCode holds is a + memtrace.io one. A self-hosted MemSync will need its own way to sign in before this rule + can widen. +- Nothing about sharing is kept in Settings or in `workspace.json`. An earlier build kept + two addresses there; they are dropped when MemCode starts. + +For tests and a local run only, two environment variables name a MemSync and a token +address instead of the list: `MEMCODE_DEV_SHARING_SERVICE` and +`MEMCODE_DEV_SHARING_TOKEN_ADDRESS`. Both must be set. No screen offers them. + +## How MemCode signs in + +```mermaid +sequenceDiagram + title Signing in to MemSync + participant App as MemCode runtime + participant Site as memtrace.io + participant Sync as MemSync + + App->>App: wait for a session refresh in flight + App->>Site: POST token address { refresh_token, device_id, session_id } + Site-->>App: { access_token, token_type: Bearer, expires_in: 600 } + App->>Sync: any call, authorization: Bearer access_token + Sync-->>App: the answer, or a status that names a rule + Note over App: The token is kept in memory and renewed a minute before it expires +``` + +- The three values are the ones MemCode sends to `/api/memcode/beta/refresh`. Nothing is + spent, so a lost reply is asked for again. +- A refresh spends the refresh token. MemCode waits for one in flight before the exchange, + and when memtrace.io still answers 401 it looks at the session once more and tries again + only if the refresh token has changed since. +- The token belongs to one sign-in. Signing out, or signing in as someone else, stops it + being used at the next call. +- When MemSync turns a token away, MemCode asks for a new one and makes the call once + more. A second refusal is shown as "did not accept this sign-in", which is what a + signing key published in the last five minutes looks like. +- Neither the session nor a token is written to `workspace.json` or sent to the window. + +## Sharing, joining and opening a project + +**The Share panel.** The Share button opens a small panel on the project: + +- An email field and **Invite**, for the owner. A project that is not shared yet is + shared by the first Invite, or by Share itself on the next call that needs it. +- **People with access**: the owner, each guest, and each open invitation. The owner can + remove a guest from the guest's menu and cancel an invitation. A guest sees the same + people, sees how many invitations are open but not whom they are for, and can leave. +- A quiet line: "Free projects hold you and 2 guests. Your own computers don't count." + The number is MemSync's. With every place taken, the email field is disabled. +- How the board stands, as in the table below. + +The button is on every project of the person's own when sharing is offered, and not on +the example project or a project in Team Sync. Signed out, the panel asks the person to +sign in; when MemSync cannot be asked, it says why and keeps naming the shared project. + +**The project switcher.** Projects shared on this computer are listed under **Shared +projects**, with a people icon. Below them come the shared projects the person is on that +are not on this computer yet, each with **Open**, and the invitations waiting for them, +each with **Join**. Join accepts the invitation and opens the project. Open and Join make +a new project here with the shared project's name and no folder, and give it the board. +Opening a shared project that is already here selects it. + +**A folder.** A project made by Open or Join has no folder on this computer. Its board +says so, with **Work on this computer**, which offers the same choices as a Team project +without a folder: an existing checkout, or a clone. Workers need one; the board does not. + +**Leaving.** A guest who leaves stays with the board on this computer, no longer shared. +The owner cannot leave; a project is deleted at memtrace.io. + +**What is kept.** A link on this computer, in `sharedProjectLinks` in `workspace.json`: +the local project, the shared project and its name when last seen, the account that made +the link, the sharing service it lives on and when. + +- A local project belongs to one shared project, and a shared project to one local + project on a computer. +- The example project cannot be shared, and neither can a project in Team Sync. Two + services must not both keep one board in step. +- A link whose shared project was deleted, or that was made under another account or on + another sharing service, is shown as such in the panel, with **Stop sharing on this + computer**. That forgets the link here and asks MemSync nothing. + +## Keeping the board in step + +The board the app shows is still the workspace file. For each connected project MemCode +also keeps a Yjs document, laid out as +[The board as one Yjs document](shared-board-layout-proposal.md) describes. MemSync holds +the log of changes to it and never reads one. + +```mermaid +sequenceDiagram + title A change made on one computer reaches another + participant Mac as MemCode on the Mac + participant Sync as MemSync + participant PC as MemCode on the PC + + Mac->>Mac: workspace saved, compared with the board as last seen + Mac->>Mac: the difference is written as an update and kept on disk + Mac->>Sync: AppendUpdates (at most 100 a call) + Sync-->>PC: WatchUpdates delivers it, numbered and dated + PC->>PC: checked, applied to the document + PC->>PC: the workspace follows, and is saved with the log position +``` + +- **Starting.** Sync runs for a project when its link belongs to the account that is + signed in and to the sharing service memtrace.io lists. It starts with MemCode, after + sharing or opening a project, and when the sign-in or the service changes. +- **The first time.** You either share your own project or join someone else's and get + their board. A computer whose board has work on it writes the board to a log that has + none, one entry an update. A computer whose project has no work takes the board from the + log as it is, lanes, custom fields and saved views included. When both have work, + nothing is merged: one sentence says so, and the project stays unshared. Share and Open + never meet this: Share starts a new shared project for the board, and Open makes a new, + empty project. One board on two computers, with the same ids, is one board. + Two computers that both find the log empty in the same seconds both write their board. + That gap is known and stays for now. Closing it needs a field in MemSync. +- **Changes made here** are found after every save of the workspace, and once when sync + starts, which is how changes made while signed out are sent later. They wait on disk + until the log has them. +- **Changes from others** are read page by page and then from a stream that stays open. + When the stream ends, MemCode reads on from the last entry it dealt with. A task that + arrives never starts a worker. +- **Offline.** Changes are kept and sent when the service answers again. MemCode tries + again after 1, 2, 5, 15, 30 and then every 60 seconds. +- **Two changes at once.** Different tasks, or different parts of one task, both stay. + Two changes to the same field end with one of the two, the same on every computer. A + description is merged, so edits in different places both stay. +- **An update that cannot be used** is left out and said so, and reading goes on. See the + layout page for what that means for the changes after it. +- **Two tasks with one identifier**, as when two computers both made MC-014 while apart: + the one that reached the log first keeps it, and the other gets the next free number. +- **A newer layout.** A board written by a newer MemCode is shown and not changed. +- **Leaving, or stopping sharing on this computer,** ends sync for that project and + deletes what was kept for it. The board stays on the computer. + +What is kept is in the profile, under `shared-boards/`, one folder per shared project: +`log.bin`, the document as the log has built it, and `sync.json`, with the log position, +the board as last seen, the changes not sent yet and the entries left out. Neither holds +a token or anything a worker wrote. + +The Share panel says how the open project's board stands, under the people: + +| State | What the person reads | +| --- | --- | +| Reading the log | Reading the shared board… | +| Nothing waits | The board is in sync. | +| Changes on their way | Sending 3 changes to the shared board… | +| The service cannot be reached | The reason, and "3 changes made here are kept on this computer and sent when it works again." | +| The project has work, and so has the shared board | "website already has work of its own, so it cannot join Website board: connect a project that has none yet." The panel offers **Stop sharing on this computer**. | +| A newer MemCode laid the board out | A newer MemCode laid this board out. Update MemCode to change it from this computer. Until then it is shown here and what you change stays on this computer. | +| The shared project is gone for this person | This shared project no longer exists, or you are no longer on it. | +| The workspace cannot be saved | The workspace could not be saved, so changes from the shared board are waiting. Free disk space, and they are taken up again. | + +Below that line, when there is something to say: "2 changes from Dana Ek on 21 November +could not be read and were left out.", "Some changes are set aside until one they build on +arrives." and "1 value is too large for the sharing service and stays on this computer." + +## What happens on a card + +Each card of a shared project has an activity log at MemSync (its ADR-0014). MemSync never +reads it; what an entry holds is MemCode's (`runtime/sharing/cards/entries.ts`). Each entry +names who may read it: everyone on the project, or only the account that wrote it, on any +of its computers (MemSync's ADR-0019). MemSync enforces that: the other computers never +receive such an entry. + +What a run writes, and who reads it (`readersOf` in `entries.ts`): + +| Entry | Who reads it | +| --- | --- | +| The run: state, what it is doing, the harness and models | Everyone | +| The person's and the worker's turns, and why a run failed | The person's own account | +| The summary of each finished round of work | Everyone | +| Its code review | Everyone | +| A file its worker made or someone shared, and what the run changed | Everyone | +| A message to the worker, what became of it, what the worker waits for | The person's own account | + +On the computer that runs a worker on a card, MemCode writes the run to the card's log as +it happens, at most once a second. Tool output, local references and review notes stay on +the computer, and paths in a home folder and tokens are blotted out of the text. + +**The summary.** Every worker's brief asks it to end its last message with a section that +starts "Summary for the project:", written for people who see neither the conversation nor +the worker's computer: what it did, what changed, how it checked it, and anything left +open, naming files by their path in the project. When a round of work finishes, that +section is the summary (the whole message when a worker leaves the heading out), and +everyone on the project reads it. A link to a file on the worker's computer becomes the +file's name, and a path in the project the path in the project (`summary.ts`). Each round, +a follow-up in the same run or a new run, adds a summary; none replaces another. + +**The changes.** When a run finishes, what it changed, as its Changes tab shows it, is +shared with the project. They are looked at again when the run's code review settles, and +shared again if they changed since. There is no button. Changes over 5 MB are not shared. + +On every other computer, a card that is opened is read from its log and followed while it +is open. A run from another computer is shown with the views MemCode has for a worker +elsewhere: + +- the card header says "On Mac"; +- the status line above the message box says "Alex Holm · Mac" and what the worker is + doing; +- the worker panel says SHARED, the harness and whose computer; +- the Code review tab shows the run's review, and the Changes tab what it changed. + +What the Conversation tab shows depends on whose run it is: + +- **Your own, from another of your computers:** the whole conversation, your turns as + "Alex Holm · Mac", and the message box continues the worker, as the next section says. +- **Someone else's:** in place of the conversation, the card's request (its description, + or its title when it has none), then each round's summary under SUMMARY with who and + when, oldest first, then how it stands: "Alex Holm is working on this on their Mac. A + summary of the work shows here when it's ready for review.", or "…working on this again + …" once there is a summary. In place of the message box: "Only Alex Holm can continue + this worker. Comment on the card to reach them." and a **Comment** button. The worker + panel says the conversation stays with Alex Holm. + +A run shows only what the account that started it wrote. A turn, a summary or a review that +someone else on the project writes into it is not shown. A computer never shows its own run +back to itself, and a run started here takes over the card. + +**Documents and images are shared on their own.** When a round of work finishes, the +files its worker saved that are made for people (Markdown, text, PDF, HTML, CSV, images, +Word, Excel and PowerPoint: `isForPeople` in `files.ts`) are shared with everyone, and a +file the worker writes again in a later round is shared again. Code and data files stay on +the computer; the Artifacts tab there lists every file with **Share** for those. A file is +at most 5 MB, and a project keeps at most 50 MB; a larger file, or one the service turns +down when the project is full, is not shared and not tried again. On other +computers, a shared file is listed among the card's files with who shared it, only its +newest version, and opening it fetches it beside the card. + +What a computer sent and what still waits is in `cards.json` in the board's folder, so a +restart sends only what is new and nothing is lost offline. An entry waiting there from a +MemCode before this change is sent for its author alone. The computer's own id for card +logs is in `shared-boards/computer.json`. + +**MemSync first.** A MemSync older than ADR-0019 ignores who an entry is for and gives +everything to everyone. The server at `sync.hosted.memtrace.io` must be updated before a +MemCode with this change is used on a shared project. + +## Continuing a worker from another computer + +A message to a worker travels in its card's log (MemSync's ADR-0015). The computer that +runs the worker, the host, decides what happens to it (ADR-0006). Only the account that +started a worker continues it: the same person on another of their computers. + +**Sending.** On a card whose worker runs on another of your computers, the message box +says "Continue the worker on your Mac…". What is sent shows in the conversation with one +line for where it stands: + +| Where it stands | The line | +| --- | --- | +| Not at MemSync yet | Sending… | +| In the log, the host has not read it | Sent to your Mac | +| Queued for the worker | Queued on your Mac | +| The worker took it | No line: it is part of the conversation, and the answer follows on each of your computers. | +| It could not reach the worker | Not delivered: the reason the host gave | + +The same lines are in the Queue tab, where such a message cannot be edited or cancelled. + +**On the host.** MemCode reads the card of every worker run here that runs now or ended in +the last three days, from where it last read, so a message sent while the host was closed +is read when it opens again, once. A message from the account that started the worker is +handled exactly as a follow-up typed on the host. A message in anyone else's name is left +alone. The host writes what became of each message into the log, for its own account. + +**Answering what the worker waits for.** A question, an approval or a plan the worker waits +for is written to the card as well, for the person's own account, and shows on their other +computer in the same panel, to answer there. A question that asks for something secret is +answered on the host only: the panel says "Answer this on your Mac". + +**Trust.** What became of a message, and what the worker waits for, count only when the +account that started the worker wrote them. A message is handled once, whatever the log +holds. Messages to a run on another computer are left alone. + +## What a person is told + +MemSync names the rule that turned a request down in `memsync-refusal` metadata. The +sentences are MemCode's own, in `src/sharing-refusals.ts`. A test fails when a rule has no +sentence. + +| Rule | Sentence | +| --- | --- | +| `no_such_project` | This shared project no longer exists, or you are no longer on it. | +| `no_such_invitation` | That invitation is no longer open. Ask the owner of the project to invite you again. | +| `no_such_guest` | That person is not a guest on this project. | +| `only_the_owner_invites` | Only the owner of a project can invite people to it. | +| `not_the_owner` | Only the owner of a project can change it. | +| `the_owner_cannot_leave` | You own this project, so you cannot leave it. You can delete it at memtrace.io. | +| `guest_limit_reached` | Every guest place on this project is taken. An invitation holds its place until it is accepted, cancelled or expires. | +| `already_on_project` | You are already on this project. | +| `already_invited` | That email address already has an open invitation to this project. | +| `invitation_expired` | This invitation has expired. Ask the owner of the project to send a new one. | +| `email_not_verified` | Invitations go to a verified email address, and the one on your Memtrace account is not verified. Verify it at memtrace.io, then accept again. | +| `invalid_project_name` | A project name is one line of text, at most 240 characters long. | +| `invalid_email` | That is not an email address. Check it and try again. | +| `invalid_update_id` | MemCode sent a board change without a usable id. This is a fault in MemCode, not something you did. | +| `empty_update` | MemCode sent an empty board change. This is a fault in MemCode, not something you did. | +| `update_too_large` | One change to the board was too large to share. Shorten the text you just added and try again. | +| `too_many_updates` | MemCode sent too many board changes at once. This is a fault in MemCode, not something you did. | +| `invalid_card_id` | MemCode named a card the sharing service cannot use. This is a fault in MemCode, not something you did. | +| `file_too_large` | That file is larger than 5 MB, which is the most a project can share in one file. | +| `project_storage_full` | This project already shares 50 MB of files, which is all it can keep. The file stays on this computer. | +| `no_such_file` | That file is no longer kept for this project. Ask whoever shared it to share it again. | +| `unknown_readers` | MemCode named readers for a card entry that the sharing service does not know. This is a fault in MemCode, not something you did. | + +The last four belong to the board log. MemCode is written so that it never meets them: +ids are made from the bytes, nothing empty is sent, a change is cut into pieces well under +the limit and a call holds at most 100. If the service names one anyway, sync for that +board stops with the sentence. `already_on_project` is worded for accepting, the only call +of MemCode's that can meet it. + +Other problems have a sentence each as well: + +| When | Sentence | +| --- | --- | +| Nobody is signed in | Sign in to Memtrace to see the projects you share. | +| memtrace.io no longer knows the session | Your Memtrace sign-in has ended. Sign in again to see the projects you share. | +| memtrace.io answers 422 | The name or email on your Memtrace account cannot be used for sharing. Change it at memtrace.io, then try again. | +| memtrace.io answers 503 | Sharing is switched off or not set up at memtrace.io right now. Try again later. | +| MemSync cannot be reached | The sharing service could not be reached. Check your connection and try again. | +| MemSync is too slow | The sharing service did not answer in time. Try again in a moment. | +| MemSync answers with trouble of its own | The sharing service is having trouble right now. Try again in a few minutes. | +| MemSync refuses the token twice | The sharing service did not accept this sign-in. Try again in a few minutes. | +| memtrace.io answers anything else, or not with a token | The sign-in for sharing answered HTTP 500. Try again later. / The sign-in for sharing did not answer with an access token. Try again later. | +| The address memtrace.io lists is not a MemSync | The address memtrace.io gave for sharing is not a sharing service. Try again later. | +| A reply cannot be read | The sharing service sent a reply MemCode could not read. Updating MemCode may help. | +| A rule MemCode does not know | The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help. | + +The call, the status and MemSync's own words go to the runtime's log on a line that starts +with `[sharing]`. + +## Where the code is + +| Piece | File | +| --- | --- | +| The use cases: overview, share, invite, cancel, remove, leave, open, join, and which boards sync | `runtime/sharing/sharing.ts` | +| Requests the window may make | `runtime/sharing/routes.ts` | +| Finding MemSync in memtrace.io's list, and the developer override | `runtime/sharing/discovery.ts` | +| The two addresses and their rules | `runtime/sharing/addresses.ts` | +| The access token: exchange, renewal, one retry | `runtime/sharing/access.ts` | +| The session shown to memtrace.io | `sessionProof` in `runtime/beta.ts` | +| Problems a person can be told about | `runtime/sharing/problems.ts` | +| MemSync's Projects API as MemCode uses it | `runtime/sharing/memsync/projects-api.ts` | +| MemSync's Boards API as MemCode uses it | `runtime/sharing/memsync/boards-api.ts` | +| A call signed with the access token, once more when the token is refused | `runtime/sharing/memsync/signed-calls.ts` | +| Board sync for one project: reading, sending, bringing two boards together | `runtime/sharing/board/sync.ts` | +| The board as a Yjs document | `runtime/sharing/board/document.ts` | +| What of a project is on the board, and what a board means for the project | `runtime/sharing/board/board.ts` | +| Update ids, the check before applying, what a document holds beyond the log | `runtime/sharing/board/updates.ts` | +| Who keeps an identifier two tasks share | `runtime/sharing/board/identifiers.ts` | +| What a connected project keeps on disk | `runtime/sharing/board/store.ts` | +| How a board stands, in words | `src/sharing-board.ts` | +| What MemCode writes into a card's log | `runtime/sharing/cards/entries.ts` | +| Writing this computer's runs, following an open card, sending and hosting messages to workers | `runtime/sharing/cards/activity.ts` | +| Where a message to a worker stands, in words; what a worker waits for, as shared | `runtime/sharing/cards/worker-messages.ts` | +| Allow and Decline on the host's card. Nothing reaches it since only a worker's own account continues it; it is to be removed | `src/components/WorkerAsks.tsx` | +| Which of a task's files may be shared, and which are shared on their own | `runtime/sharing/cards/files.ts` | +| A round of work's summary, from the worker's last message | `runtime/sharing/cards/summary.ts` | +| MemSync's Cards API as MemCode uses it | `runtime/sharing/memsync/cards-api.ts`, `cards-contract.ts`, `cards.proto` | +| A run from a card's log, in the shape the card's views take, and what someone else's run says in place of its conversation | `src/sharing-cards.ts` | +| Someone else's run: the request, each round's summary, how it stands | `src/components/OthersRun.tsx` | +| The card's files on the computer that ran the worker, with Share for the rest | `src/components/ShareFromCard.tsx` | +| gRPC over Node's own HTTP/2 | `runtime/sharing/memsync/grpc.ts` | +| Protocol Buffers on the wire | `runtime/sharing/memsync/wire.ts` | +| The contract, and the part of it MemCode uses | `runtime/sharing/memsync/projects.proto`, `projects-contract.ts`, `boards.proto`, `boards-contract.ts` | +| Rule names and sentences | `src/sharing-refusals.ts` | +| What the window knows of sharing | `src/sharing.ts` | +| The Share button and panel, the switcher's shared projects, the folder notice | `src/components/ShareProject.tsx` | + +MemCode makes nine of the eleven Projects calls: `StartProject`, `ListProjects`, +`GetProject`, `InvitePerson`, `ListInvitations`, `AcceptInvitation`, `CancelInvitation`, +`RemoveGuest` and `LeaveProject`. Renaming and deleting stay at memtrace.io. It makes all +three Boards calls, `AppendUpdates`, `ReadUpdates` and +`WatchUpdates`, and all five Cards calls. A Cards reply can be 6 MiB, so the client takes +replies that large. + +One package was added: `yjs` 13.6.33, with `lib0` and `isomorphic.js` that it needs. They +are in the lock file and in the third-party notices. The gRPC client is still MemCode's +own, over `node:http2`, because the app otherwise has no gRPC dependency. The contract +files are written by hand; `tests/sharing-wire.test.ts` reads the `.proto` files and fails +when the two disagree, and checks the codec against bytes made by `protoc`. + +### When the contract changes + +`runtime/sharing/memsync/projects.proto` and `boards.proto` are copies of the files in +`proto/memsync/v1/` in the `memsync` repository, taken on 21 November 2026. Copy the newer +file over it and run: + +```sh +node --import tsx --test tests/sharing-wire.test.ts +``` + +The test names every message and call that no longer matches. + +## Checks + +```sh +node --import tsx --test tests/sharing*.test.ts +``` + +One file runs MemCode's client against a real `memsync-server`. It is skipped unless both +variables are set: + +```sh +MEMSYNC_SERVER_BINARY=/path/to/memsync/target/release/memsync-server MEMSYNC_TEST_DATABASE_URL=postgres://memsync@127.0.0.1:54329/postgres node --import tsx --test tests/sharing-real-memsync.test.ts +``` + +`MEMSYNC_TEST_DATABASE_URL` names a PostgreSQL server where tests may create databases, +as in the `memsync` repository. The test makes a database of its own with `psql` and drops +it, so nothing that already exists there is touched. Never point it at a server that holds +real data. `MEMSYNC_TEST_PSQL` names another `psql` when the one on the PATH will not do. + +The same scenarios run against a stand-in service in `tests/support/memsync-stand-in.ts` +on every `npm test`. Twelve of the thirteen project rules are reached against the real +server. `invitation_expired` is reached only on the stand-in, where days can be made to +pass. + +Board sync has nine scenarios with two computers that run against both: a board written +out and taken by a second computer, a goal, a cycle and a task made on one showing on the +other while both run, changes in both directions, offline and a restart, +changes made while sync was not running, two boards that stay two, two tasks numbered +alike, and a guest who is taken off the project. Sixteen more run against the stand-in only, +most because they need a service that can be made to misbehave: an answer that is lost, +an update damaged in the log, bytes that are not what their id says, an update that reads +and cannot be applied, a newer layout, a change the service refuses, a call it never +answers, MemCode stopped before and after the workspace file was written, a full disk and +a stream that is cut. `tests/sharing-runtime.test.ts` runs two whole runtimes against the +stand-in, through the same requests the window makes. + +43 deliberate breakages of board sync were run against these tests. 42 make a test fail. +One is not caught: the line in `runtime/app.ts` that hands board sync the workspace save. +What that line relies on, that `LocalStore.save` reads the workspace at the call and +writes it after the step it is given, is covered in `tests/sharing-workspace-save.test.ts`. + +What happens on a card has five Cards client scenarios and eight card activity scenarios, +which run against the stand-in and against a real `memsync-server` that serves Cards +(the one built on 22 November does): entries numbered and signed per card, a watched card, +a 5 MB file in one reply, every refusal by its rule name, the 50 MB limit; a run shown live +on the other computer with who runs it, only what changed sent again, the review, a turn +and a review forged by a guest not shown, the same person on two computers, offline and a +restart, a shared file, and a task whose id is not a UUID. + +Continuing a worker from another computer has seven more card activity scenarios, against +both: the person's own follow-up taken at once and answered on both computers, someone +else's waiting until allowed, one declined, a delivery forged by a guest not believed, a +message sent while the host was closed taken once when it opens (and once again even when +read from the start), a question answered from the other computer with a secret one kept +to the host, and a sender who joined after the host last looked named rather than called +"someone". Two whole runtimes check that a follow-up typed on the PC is queued for the +Mac's worker and shown on the PC as "Queued on your Mac". + +## Trying it on one computer + +`scripts/shared-projects-local.mts` runs the real runtime and the real app window in a +browser, signed in through a memtrace.io on the same computer. + +What is real: the runtime, its beta sign-in and refresh, the token exchange, the calls to +`memsync-server` and the app's own screens. What stands in: the native shell, whose calls +the script answers; the person in the browser, whose approval the script gives with a +session cookie; and the code engine, which is switched off so that nothing is downloaded +and no installed Memtrace is touched. + +1. Start a throwaway PostgreSQL and create two databases, one for the site and one for + MemSync. +2. Run memtrace.io from a branch that has `POST /api/memcode/memsync/token`, with + `MEMCODE_BETA_ENABLED=1` and a signing key. The `memtrace` repository describes this in + `memtrace-ui/docs/memsync-access-tokens.md` and `memcode-projects.md`. +3. Start `memsync-server` after the site, with `MEMSYNC_TOKEN_KEYS_URL` set to the site's + `/api/memcode/jwks`. +4. Give the site a signed-in, approved person: a `user`, an approved `app_users` row and a + `session`, as `e2e/seed.mjs` in `memtrace-ui` does. Their signed session cookie is what + the script needs. +5. Start MemCode: + + ```sh + MEMCODE_LOCAL_SITE=http://127.0.0.1:3000 MEMCODE_LOCAL_SITE_COOKIE= node --import tsx scripts/shared-projects-local.mts --port 5310 + ``` + +6. Open the address it prints and choose **Connect Memtrace beta** under Account in + Settings. + +The script sends MemCode's requests to memtrace.io to the local site, so MemCode finds +MemSync in the site's `/api/memcode/services`. Give that list a `sharing` entry with the +local MemSync and `http://localhost:/api/memcode/memsync/token`. Or start the +script with `MEMCODE_DEV_SHARING_SERVICE` and `MEMCODE_DEV_SHARING_TOKEN_ADDRESS` set. + +Click **Share** and invite someone. A second run on another port, with another +`--profile` folder, is a second computer: sign it in as the same person and **Open** the +project from the switcher, and what is done on one board shows on the other. A run with +another person's cookie is a guest's computer: the invitation is in its switcher, with +**Join**. + +Stopping `memsync-server` shows the offline line and the count of changes that wait. +Starting it again sends them, within a minute. + +To try what happens on a card without running a model, start the computer that runs the +worker with `--stand-in-worker`. It answers follow-ups by itself, from this computer or +another, a couple of seconds after they are picked up. It also adds `POST /dev/worker-turn`, +which plays a worker on a task: `{ "taskId": "…", "text": "…", "state": "running" | "finished", "file": { "name": +"report.html", "text": "…" } }`. Open the card on the other computer and watch it follow. +In this browser run an HTML file shows a blank preview on both computers: the native shell +draws HTML previews, and the script stands in for it. + +## Choices that are not confirmed + +1. **Where sharing sits.** A Share button at the top right of a project, with the + people on it beside it, and shared projects and invitations in the project switcher. + No sidebar entry and no Settings fields. +2. **MemCode finds MemSync in memtrace.io's list of services**, asked at most once a + minute. A list that cannot be read means no Share button until the next try. +3. **The sign-in address must be at www.memtrace.io or on this computer.** +4. **No new package.** gRPC and Protocol Buffers are written against Node's own HTTP/2, + and checked against the `.proto` file. The website uses Connect. +5. **One local project per shared project on a computer, and one shared project per local + project.** +6. **A project in Team Sync cannot be shared** until it has left its team. +7. **Share starts a shared project with the local project's name.** There is no step to + name it, and nothing to confirm before the first invitation goes. +8. **The window is given names and account ids**, the ids so the owner can remove a + guest. Whom an invitation is for is shown to the owner only; a guest sees how many are + open. +9. **Every sentence** on this page and on the screens. +10. **Ten seconds** of patience for a MemSync call and fifteen for the token exchange. +11. **A token is renewed a minute before it expires**, or at half its life when it lives + under two minutes. +12. **Open and Join make a project with no folder.** The board works at once; a folder is + chosen when someone wants workers here. +13. **The local-run script is in the repository**, with a stand-in for the native shell. + +For board sync, beside what the [layout page](shared-board-layout-proposal.md) holds: + +14. **Sync starts by itself** for every shared project. There is no switch per project. +15. **Where the board is kept on disk**: `shared-boards/` in the profile. +16. **Where a project and the log hold an entry with the same id, the log's is taken.** + That is one board on two computers, or a project that is connected again. +17. **Sharing waits up to eight seconds** for board sync to say how the two boards stand, + and takes the link back when both have work. When the service cannot be asked in + that time, the link stays and the Share panel says it later. +18. **A project that joins takes the board's lanes, custom fields and saved views** in + place of its own. +19. **How long MemCode waits before trying again**: 1, 2, 5, 15, 30, then 60 seconds. +20. **A comment in a shared project is by the Memtrace account**, with the name the + sharing service has for it. Before, it was by "You". +21. **A task that a worker on this computer is on is not taken off the board here** when + someone else deletes it. It is back for everyone once it changes here. +22. **Every sentence** in the table of states above. + +For what happens on a card: + +23. **A card is read when it is opened and followed while open**, not for every card all + the time. The board does not show who is running what across the project. +24. **Documents and images a worker makes are shared on their own; code and data with one + click each** (Alex, 23 November 2026: clicking Share on images, Markdown, slides and + sheets "seems weird"; it is "not .js files"). Superseded the one-click-each rule. A + run's changes are shared when it finishes, as a file of the Changes tab's own format, + not a Git patch. +25. **A run's turns and review count only from the account that wrote its first entry.** +26. **The person's turns of a run from elsewhere carry the run owner's name.** +27. **This computer is named by its kind, "Mac", "Windows" or "Linux"**, never its host name. +28. **A run is written at most once a second**, so a long streamed answer is sent a few + times over as it grows. +29. **Only the person who runs a worker reads its conversation** (Alex, 23 November 2026: + "I can't see what the agents has been had conversations about" in Linear). Everyone + else reads how it stands and its summary. Why a run failed is the person's too. +30. **The summary is the section of the run's last message headed for the project**, + which the brief asks for, or the whole message without one. It is not written by + another model. Links and paths on the worker's computer are turned into file names, + since nobody else can open them (Alex: the first summaries were "not very user + friendly"). +31. **A run's changes are looked at when it ends and when its code review settles**, not + on every save. + +For continuing a worker from another computer: + +32. **The host reads the cards of workers that run now or ended in the last three days.** + A message to an older run waits until it is run again. +33. **No one-time approval for a person's own second computer.** Signing in to the same + account on both is the approval, as ADR-0015 says. +34. **Nobody else continues a worker**, not even after its person allows it. A guest + comments on the card. +35. **A message sent from another computer cannot be edited or cancelled**: the log keeps + what was written. +36. **A secret answer never travels.** The question shows; it is answered on the host. + +For what others read of a run: + +37. **Others see the request above the summaries**, and every round of work keeps its + own summary (Alex, 23 November 2026). +38. **A file shared again is listed once, as its newest version**, by its name and who + shared it. +39. **Deleting a project in MemCode never deletes it for others** (Alex, 23 November 2026: + "too many projects without being able to delete them"). A shared project is + disconnected from this computer and stays shared; deleting it for everyone stays at + memtrace.io. A project still in a Team Sync team is left from its Team page first. + +## Not built + +- **Claims, and who is running what across the project.** A person sees who runs a worker + on a card when they open it. +- **Starting a new worker on someone else's computer.** A message continues a worker that + ran there; it does not start one. +- **Hiding a review or a file that someone else on the project shared into a card.** A + file shows who shared it; it is not refused. +- What the [layout page](shared-board-layout-proposal.md#not-built) lists for the board. +- Anything for organization projects. MemSync has none yet. +- Moving a Team Sync project to a shared project. +- Renaming or deleting a shared project from MemCode. Both are at memtrace.io. +- A notice in the app when an invitation arrives. The switcher shows it when opened. +- Taking back a shared project that Share started when writing its board then failed. It + stays at MemSync, empty, and the next Share starts another. diff --git a/package-lock.json b/package-lock.json index 80cea25..596e28d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "memcode", - "version": "0.4.0-beta.20", + "version": "0.4.0-beta.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "memcode", - "version": "0.4.0-beta.20", + "version": "0.4.0-beta.21", "license": "PolyForm-Noncommercial-1.0.0", "dependencies": { "@aiden0z/pptx-renderer": "1.4.0", @@ -29,6 +29,7 @@ "react-markdown": "10.1.0", "read-excel-file": "9.3.17", "remark-gfm": "4.0.1", + "yjs": "13.6.33", "zod": "4.6.7" }, "devDependencies": { @@ -3530,6 +3531,16 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "license": "ISC" }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "license": "MIT", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/jose": { "version": "6.2.17", "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", @@ -3599,6 +3610,27 @@ "safe-buffer": "~5.1.0" } }, + "node_modules/lib0": { + "version": "0.2.120", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.120.tgz", + "integrity": "sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==", + "license": "MIT", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/lie": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", @@ -6136,6 +6168,23 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/yjs": { + "version": "13.6.33", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz", + "integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.99" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", diff --git a/package.json b/package.json index 3e24520..b082f63 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "memcode", - "version": "0.4.0-beta.20", + "version": "0.4.0-beta.21", "license": "PolyForm-Noncommercial-1.0.0", "private": true, "description": "The local Fleet Agentic Worker Suite, powered by Memtrace.", @@ -39,6 +39,7 @@ "react-markdown": "10.1.0", "read-excel-file": "9.3.17", "remark-gfm": "4.0.1", + "yjs": "13.6.33", "zod": "4.6.7" }, "devDependencies": { diff --git a/runtime/agents/acp-models.ts b/runtime/agents/acp-models.ts index 31f6b67..d5bcbb5 100644 --- a/runtime/agents/acp-models.ts +++ b/runtime/agents/acp-models.ts @@ -5,21 +5,49 @@ type Json = Record; const rows = (value: unknown): Json[] => Array.isArray(value) ? value.filter(row => row && typeof row === "object") : []; const configs = (session: Json) => rows(session.configOptions); const modelConfig = (session: Json) => configs(session).find(option => option.category === "model" || option.id === "model"); -function choices(option?: Json): Json[] { - return rows(option?.options).flatMap(row => Array.isArray(row.options) ? choices(row) : [row]); +function choices(option?: Json, group?: string): Json[] { + return rows(option?.options).flatMap((row) => { + if (Array.isArray(row.options)) { + const nextGroup = + typeof row.name === "string" + ? row.name + : typeof row.group === "string" + ? row.group + : group; + return choices(row, nextGroup); + } + const leafGroup = typeof row.group === "string" ? row.group : group; + return [leafGroup !== undefined ? { ...row, group: leafGroup } : row]; + }); } /** Opaque ACP IDs come from this installed provider. No guessed model names. */ export function standardACPCatalog(session: Json): ModelOption[] { const option = modelConfig(session); const current = option?.currentValue ?? session.models?.currentModelId; - const offered = option ? choices(option).map(row => ({ id: row.value, label: row.name ?? row.label })) - : rows(session.models?.availableModels).map(row => ({ id: row.modelId, label: row.name })); + const offered = option + ? choices(option).map((row) => ({ + id: row.value, + label: row.name ?? row.label, + group: row.group, + })) + : rows(session.models?.availableModels).map((row) => ({ + id: row.modelId, + label: row.name, + group: row.group, + })); const seen = new Set(); - return offered.flatMap(row => { + return offered.flatMap((row) => { if (typeof row.id !== "string" || !row.id || row.id.length > 256 || seen.has(row.id)) return []; seen.add(row.id); - return [{ id: row.id, label: typeof row.label === "string" ? row.label : row.id, source: "acp" as const, isDefault: row.id === current }]; + const group = typeof row.group === "string" && row.group ? row.group : undefined; + return [{ + id: row.id, + label: typeof row.label === "string" ? row.label : row.id, + ...(group ? { group } : {}), + source: "acp" as const, + isDefault: row.id === current, + }]; }); } diff --git a/runtime/agents/cursor.ts b/runtime/agents/cursor.ts index a762a17..18077df 100644 --- a/runtime/agents/cursor.ts +++ b/runtime/agents/cursor.ts @@ -192,17 +192,44 @@ export function startStandardACPSession(transport: ACPTransport, options: AgentS return runCursorSession(options, undefined, transport); } -export async function probeStandardACPCatalog(transport: ACPTransport, command: Command): Promise { +export async function probeStandardACPCatalog( + transport: ACPTransport, + command: Command, + probeOptions?: { strictStdout?: boolean }, +): Promise { const cwd = await mkdtemp(join(tmpdir(), `memcode-${transport.id}-catalog-`)); let models: ModelOption[] = []; + let inspected = false; + let stdoutNoiseError: string | undefined; try { - const session = runCursorSession({ command, cwd, env: childEnv(), model: "", effort: "low", prompt: "", briefPath: "", toolArgs: [], - onEvent: () => {}, requestInput: async () => ({ cancelled: true }), - }, result => { models = standardACPCatalog(result); }, transport); - const timer = setTimeout(() => { void session.stop(); }, 15000); + const session = runCursorSession({ + command, + cwd, + env: childEnv(), + model: "", + effort: "low", + prompt: "", + briefPath: "", + toolArgs: [], + onEvent: (event) => { + if (probeOptions?.strictStdout && event.type === "error" && !stdoutNoiseError) { + stdoutNoiseError = event.message; + } + }, + requestInput: async () => ({ cancelled: true }), + }, (result) => { + inspected = true; + models = standardACPCatalog(result); + }, transport, probeOptions?.strictStdout === true); + const timer = setTimeout(() => { void session.stop(); }, 25000); try { const result = await session.completion; if (result.exitCode !== 0) throw Error(result.error || `${transport.name}'s model catalog did not respond.`); + if (probeOptions?.strictStdout) { + if (stdoutNoiseError) throw Error(stdoutNoiseError); + if (!inspected) throw Error(`${transport.name}'s model catalog did not respond cleanly.`); + if (models.length === 0) throw Error(`${transport.name} returned an empty model catalog.`); + } } finally { clearTimeout(timer); } return models; } finally { @@ -210,7 +237,20 @@ export async function probeStandardACPCatalog(transport: ACPTransport, command: } } -function runCursorSession(options: AgentSessionOptions, inspect?: (session: Json) => void, transport?: ACPTransport): AgentSession { +/** A JSON-RPC 2.0 request, notification or response, as ACP sends them. */ +function isJsonRpcMessage(message: Json): boolean { + if (message.jsonrpc !== "2.0") return false; + if (typeof message.method === "string") return true; + return hasId(message) && ("result" in message || "error" in message); +} + +function runCursorSession( + options: AgentSessionOptions, + inspect?: (session: Json) => void, + transport?: ACPTransport, + /** Treat any stdout line that is not a JSON-RPC message as an error. */ + strictStdout = false, +): AgentSession { const brand = transport?.name ?? "Cursor"; // Current ACP ignores --auto-review even though interactive Cursor supports it. // Never silently run an allowlist/bypass session labelled as Smart auto. @@ -646,7 +686,18 @@ function runCursorSession(options: AgentSessionOptions, inspect?: (session: Json const lines = createInterface({ input: child.stdout! }); lines.on("line", (line) => { try { - incoming(record(JSON.parse(line))); + const message = record(JSON.parse(line)); + // JSON log lines such as {"message":"starting"} are ignored by incoming(); + // a strict probe must still see that stdout is not a clean ACP stream. + if (strictStdout && !isJsonRpcMessage(message)) { + emit({ + type: "error", + message: `${brand} wrote a JSON line that is not an ACP message to stdout.`, + fatal: false, + }); + return; + } + incoming(message); } catch { emit({ type: "error", diff --git a/runtime/agents/standard-acp.ts b/runtime/agents/standard-acp.ts index 70a2762..79a5e22 100644 --- a/runtime/agents/standard-acp.ts +++ b/runtime/agents/standard-acp.ts @@ -1,14 +1,33 @@ import { probeStandardACPCatalog, startStandardACPSession, type ACPTransport } from "./cursor"; import type { AgentSessionOptions } from "./types"; import type { Command } from "../commands"; +import { normalizeDshProfile } from "../dsh-profiles"; import { join } from "node:path"; import { writeFile } from "node:fs/promises"; export type StandardHarness = "copilot" | "dsh"; -export function standardTransport(id: StandardHarness, options?: Pick): ACPTransport { +export function standardTransport( + id: StandardHarness, + options?: Partial> & { + allowStaging?: boolean; + }, +): ACPTransport { return id === "copilot" - ? { id, name: "GitHub Copilot", args: ["--acp", "--stdio", ...(options ? ["--effort", options.effort] : [])] } - : { id, name: "DeepSeek Harness", args: ["--profile", "acp"] }; + ? { + id, + name: "GitHub Copilot", + args: ["--acp", "--stdio", ...(options?.effort ? ["--effort", options.effort] : [])], + } + : { + id, + name: "DeepSeek Harness", + args: [ + "--profile", + normalizeDshProfile(options?.dshProfile, { + allowStaging: options?.allowStaging, + }), + ], + }; } export function startStandardSession(id: StandardHarness, options: AgentSessionOptions) { if (options.localModel) throw Error("The local-model override currently supports Codex with Ollama."); @@ -18,12 +37,30 @@ export function startStandardSession(id: StandardHarness, options: AgentSessionO env: { ...options.env, ...(id === "dsh" ? { DSH_PERMISSION_MODE: options.permissionMode === "full-access" ? "danger-full-access" : "workspace-write" } : {}) }, }); } -export function probeStandardCatalog(id: StandardHarness, command: Command) { - return probeStandardACPCatalog(standardTransport(id), command); +// Async, so an invalid profile name rejects instead of throwing before a +// caller's .catch() is attached. +export async function probeStandardCatalog( + id: StandardHarness, + command: Command, + dshProfile?: string, + options?: { strictStdout?: boolean; allowStaging?: boolean }, +) { + return probeStandardACPCatalog( + standardTransport( + id, + id === "dsh" ? { dshProfile, allowStaging: options?.allowStaging } : undefined, + ), + command, + options, + ); } /** Separate reviewer process, no MCP servers, shell, edits or agent tools. */ -export async function readonlyACPTransport(id: StandardHarness, capsule: string): Promise { +export async function readonlyACPTransport( + id: StandardHarness, + capsule: string, + dshProfile?: string, +): Promise { if (id === "copilot") return { id, name: "GitHub Copilot", args: ["--acp", "--stdio", "--available-tools=view", "--disable-builtin-mcps", "--no-custom-instructions", "--no-auto-update"], }; @@ -39,5 +76,9 @@ export function apply(ctx) { { id: "sandbox-policy", config: { mode: "read-only", workspaceRoot: capsule } }, { insert: [{ id: "memcode-readonly-review", name: plugin }] }, ]), { mode: 0o600 }); - return { id, name: "DeepSeek Harness", args: ["--profile", "acp", "--patch", patch] }; + return { + id, + name: "DeepSeek Harness", + args: ["--profile", normalizeDshProfile(dshProfile), "--patch", patch], + }; } diff --git a/runtime/agents/types.ts b/runtime/agents/types.ts index 5972f00..c504a3e 100644 --- a/runtime/agents/types.ts +++ b/runtime/agents/types.ts @@ -42,6 +42,7 @@ export interface AgentSessionOptions { contextConfig?: string; toolArgs: string[]; localModel?: boolean; + dshProfile?: string; permissionMode?: import("../../src/permissions").PermissionMode; onEvent(event: AgentEvent): void; requestInput( diff --git a/runtime/app.ts b/runtime/app.ts index 820bdbd..ce9bdd1 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -11,10 +11,11 @@ import { randomUUID } from "node:crypto"; import { z } from "zod"; import { newRunbook } from "../src/runbook"; import { repoRelativePath } from "./context/source"; -import type { AppState, Project, WorkItem } from "../src/shared"; +import type { AppState, DshSetupStatus, Project, WorkItem } from "../src/shared"; import { maxWorkerSlots } from "../src/worker-slots"; import { isActive } from "../src/domain"; import { LocalStore, exists, findCommand, git, now, within } from "./local"; +import { findDesktopApp, refreshWindowsUserPath } from "./commands"; import { observePersistence } from "./persistence"; import { MemtraceEngine } from "./memtrace"; import { ensureProjectRepository } from "./project-repository"; @@ -26,7 +27,21 @@ import { reconcileArtifacts } from "./artifact-catalog"; import { WorkerManager } from "./workers"; import { PreviewManager } from "./preview"; import { localURL } from "./urls"; -import { discoverHarnesses } from "./catalog"; +import { discoverHarnesses, invalidateHarnessCache } from "./catalog"; +import { probeStandardCatalog } from "./agents/standard-acp"; +import { + createDshAcpProfile, + inspectDshProfiles, + normalizeDshProfile, +} from "./dsh-profiles"; +import { inspectDshDesktopCli, installDshDesktopCli } from "./dsh-desktop"; +import { + applyDshMigration, + diffDshDesktopModels, + dryRunDshMigration, + type DshMigrationPlan, +} from "./dsh-migration"; +import { DshSetupGate } from "./dsh-setup-gate"; import { planDefinedStory, readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { qualificationRequestFingerprint } from "./qualification"; import { registerPlanning } from "./planning"; @@ -65,6 +80,13 @@ import { createMemtraceIdentityProofProvider } from "./team-identity"; import { discoverOfficialTeamService } from "./team/discovery"; import { createBetaAuthorization } from "./beta-auth"; import { MemCodeBeta, nativeBetaStorage } from "./beta"; +import { Sharing } from "./sharing/sharing"; +import { sharingFinder } from "./sharing/discovery"; +import type { SharingSettings } from "../src/sharing"; +import { shareableFile } from "./sharing/cards/files"; +import { + registerSharing, +} from "./sharing/routes"; import { ManagedMemcodeEngine } from "./managed-engine"; import { ManagedRetrievalAssistant } from "./context/managed-assistant"; import { ProductTelemetry, observeTelemetryMutation } from "./telemetry"; @@ -139,7 +161,11 @@ export async function createRuntime( appPath: string, host: NativeHost, emit: Emit, - options?: { discoverHarnesses?: typeof discoverHarnesses }, + options?: { + discoverHarnesses?: typeof discoverHarnesses; + /** Where sharing lives. Tests name a stand-in instead of asking memtrace.io. */ + findSharing?: () => Promise; + }, ) { const discover = options?.discoverHarnesses ?? discoverHarnesses; const store = new LocalStore(dataDir); @@ -149,6 +175,10 @@ export async function createRuntime( let betaNeedsAnalysis = false; let betaReady = false; let requireFreshWorkerContext = false; + // Setup changes, dsh workers and dsh reviewers never overlap. + const dshGate = new DshSetupGate(); + // Only the most recent successful dry-run can be applied, and only once. + let dshPlan: { id: string; plan: DshMigrationPlan } | null = null; const qaProfile = process.env.MEMCODE_NATIVE_TEST_PROFILE === "1" || !!process.env.NODE_TEST_CONTEXT; @@ -187,17 +217,19 @@ export async function createRuntime( let dispatchQueued = () => {}; let closed = false; let team: TeamSyncClient | undefined; + let sharing: Sharing | undefined; let persistenceFailed = false; - const changed = () => { + /** Tells the window once the workspace is written, and says so when it could not be. */ + const saved = (write: () => Promise, then?: () => Promise) => { const pending = (async () => { - await team?.capture(); - await store.save(); + await write(); emit("workspace:state", store.state); dispatchQueued(); if (persistenceFailed) { persistenceFailed = false; emit("workspace:save-status", { state: "saved" }); } + await then?.(); })(); return observePersistence(pending, (error) => { persistenceFailed = true; @@ -212,6 +244,15 @@ export async function createRuntime( }); }); }; + const changed = () => + saved( + async () => { + await team?.capture(); + await store.save(); + }, + // A board shared through the sharing service looks at what was just saved. + async () => sharing?.workspaceSaved(), + ); let reconcilingArtifacts: Promise | undefined; let artifactsCheckedAt = 0; const reconcileCatalog = () => { @@ -249,10 +290,15 @@ export async function createRuntime( release: (taskId, projectId) => team?.release(taskId, projectId) ?? Promise.resolve(), }, - () => { + (harness) => { appUpdateGate.assertMayStart(); beta?.assertMayStart(); if (!beta?.usesBeta()) connections.account.assertMayStart(); + if (harness === "dsh" && dshGate.operation) { + throw new Error( + "Wait for DeepSeek Harness setup to finish before starting a DeepSeek Harness worker.", + ); + } }, (project) => betaReady && @@ -335,7 +381,11 @@ export async function createRuntime( await codeReviews.discuss(item.id, command.reviewRunId!, command.text, {id: command.id, actor: command.author}); } }, - onWorkerActivity: () => emit("workspace:state", store.state), + onWorkerActivity: () => { + emit("workspace:state", store.state); + // What a worker on a shared project does goes to its card's log as it happens. + sharing?.workerActivity(); + }, identityProof: teamIdentity, identityAvailable: teamIdentity.available, serviceDiscovery: () => discoverOfficialTeamService(), @@ -693,6 +743,8 @@ export async function createRuntime( }, changed: (status) => { emit("beta:status", status); + // Signing in or out decides which connected boards are synchronized. + if (!closed) void sharing?.syncBoards(); if (!status.loginPending && !closed) { if ( betaNeedsAnalysis && @@ -723,6 +775,56 @@ export async function createRuntime( } }, }); + // Sharing shows memtrace.io the same session, and holds no credential of its own. + sharing = new Sharing({ + state, + changed, + session: () => beta!.sessionProof(), + // memtrace.io lists where the sharing service is. No list entry: no sharing. + addresses: options?.findSharing ?? sharingFinder(), + makeProject: async (name) => { + const item: Project = { + id: randomUUID(), + name: name.slice(0, 80), + description: "", + // A shared board needs no folder. One is chosen when work starts here. + path: null, + branch: "main", + analysis: "idle", + createdAt: now(), + }; + store.state.projects.push(item); + initializeCodeReviewWorkflow(store.state, item.id); + store.state.activeProjectId = item.id; + await changed(); + return item; + }, + boardsFolder: join(store.dir, "shared-boards"), + // The workspace is read at this very call, so a board change is saved whole or not at all. + saveWorkspace: (first) => saved(() => store.save(first)), + shown: () => emit("workspace:state", store.state), + cards: { + reviewOf: (taskId) => + codeReviews?.get(taskId).catch(() => null) ?? Promise.resolve(null), + shareableFile: (taskId, artifactId) => + shareableFile(store.dir, store.state, taskId, artifactId), + changesOf: (taskId) => readDisplayedWorkerChanges(task(taskId)), + filesFolder: (taskId) => join(store.dir, "captures", taskId), + // A follow-up from another computer is taken exactly as one typed here. + continueWorker: async (taskId, message) => { + const item = task(taskId); + if (item.messages.some((one) => one.id === message.id)) return; + item.messages.push(message); + item.updatedAt = message.at; + workers.enqueue(item, message.id); + await changed(); + workers.dispatchQueued(); + }, + answerWorker: (taskId, inputId, response) => + workers.inputs.respond(taskId, inputId, response), + }, + }); + registerSharing(register, sharing); register("beta:status", z.undefined(), () => beta!.status()); register("beta:connect", z.undefined(), () => beta!.connect()); register("beta:cancel", z.undefined(), () => beta!.cancel()); @@ -773,7 +875,7 @@ export async function createRuntime( const measurement = { ...current, scope: current.scope?.slice() }; const measuredRequest = qualificationRequestFingerprint(measurement); const [installed, evidence, calibration, languageModel] = await Promise.all([ - discover(), + discover(false, undefined, { dshProfile: store.state.settings.dshProfile }), engine.qualify( epicAnalysisProject(project(measurement.projectId), measurement), measurement, @@ -820,9 +922,247 @@ export async function createRuntime( host.call("installation_show_applications", {}), ); register("connection:refresh-catalog", z.undefined(), async () => { - await discoverHarnesses(true); + if (process.platform === "win32" && !(await findCommand("dsh"))) { + await refreshWindowsUserPath(); + } + await discoverHarnesses(true, undefined, { + dshProfile: store.state.settings.dshProfile, + }); return store.runtime(); }); + const resolveDshCommand = async () => { + let command = await findCommand("dsh"); + if (!command && process.platform === "win32") { + await refreshWindowsUserPath(); + command = await findCommand("dsh"); + } + return command; + }; + const dshSetupStatus = async (): Promise => { + const [command, desktopAppPath, profiles] = await Promise.all([ + resolveDshCommand(), + findDesktopApp("dsh"), + inspectDshProfiles(store.state.settings.dshProfile), + ]); + const desktopCli = desktopAppPath + ? await inspectDshDesktopCli(desktopAppPath) + : undefined; + return { + cliInstalled: !!command, + cliPath: command?.command ?? null, + desktopAppPath: desktopAppPath ?? null, + ...(desktopCli ? { desktopCli } : {}), + ...profiles, + }; + }; + const assertNoActiveDshWorker = () => { + if ( + store.state.tasks.some( + (item) => !item.example && item.harness === "dsh" && isActive(item), + ) + ) + throw new Error( + "Stop active DeepSeek Harness workers before changing its CLI, profile, or model setup.", + ); + }; + const withDshSetupLock = async ( + operation: string, + fn: () => Promise, + options: { readOnly?: boolean } = {}, + ): Promise => { + if (!options.readOnly) assertNoActiveDshWorker(); + try { + return await dshGate.run(operation, fn, { mutates: !options.readOnly }); + } finally { + dispatchQueued?.(); + } + }; + /** + * A model chosen from one profile's catalog may not exist in another. After + * a profile or its providers change, drop dsh overrides the new catalog does + * not offer, so later dsh tasks cannot fail model selection. + */ + const revalidateDshOverrides = async () => { + const runtime = await store.runtime(); + const offered = new Set( + runtime.harnesses.find((item) => item.id === "dsh")?.models.map((model) => model.id) ?? [], + ); + // An unavailable catalog cannot prove an override wrong; keep them. + if (offered.size === 0) return runtime; + let dropped = false; + const settings = store.state.settings; + if (settings.defaultHarness === "dsh" && !settings.localModel && settings.model && !offered.has(settings.model)) { + settings.model = ""; + dropped = true; + } + for (const item of store.state.tasks) + if ( + !item.example && + item.harness === "dsh" && + item.stage !== "done" && + item.modelOverride && + !offered.has(item.modelOverride) + ) { + item.modelOverride = null; + dropped = true; + } + if (dropped) await changed(); + return runtime; + }; + const resolveDshTargetProfile = async (targetProfile?: string) => + targetProfile?.trim() + ? normalizeDshProfile(targetProfile) + : (await inspectDshProfiles(store.state.settings.dshProfile)).activeProfile; + register("dsh:setup-status", z.undefined(), () => dshSetupStatus()); + register("dsh:install-cli", z.undefined(), () => + withDshSetupLock("install-cli", async () => { + const desktopAppPath = await findDesktopApp("dsh"); + if (!desktopAppPath) + throw new Error( + "DeepSeek Harness Desktop was not found on this computer.", + ); + const installed = await installDshDesktopCli(desktopAppPath); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + store.runtime(), + ]); + const discoverable = !installed.installed || status.cliInstalled; + return { + installed: installed.installed && status.cliInstalled, + ...(installed.needsDesktopMenu !== undefined + ? { needsDesktopMenu: installed.needsDesktopMenu } + : {}), + message: discoverable + ? installed.message + : "DeepSeek Harness Desktop registered the CLI, but MemCode could not discover the launcher yet. Restart MemCode or verify dsh is on PATH.", + status, + runtime, + }; + }), + ); + register( + "dsh:create-profile", + z.object({ name: nonempty.max(64) }).strict(), + ({ name }) => + withDshSetupLock("create-profile", async () => { + const normalized = normalizeDshProfile(name); + const command = await resolveDshCommand(); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before creating an ACP profile.", + ); + const profile = await createDshAcpProfile(command, normalized); + store.state.settings.dshProfile = profile; + dshPlan = null; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + revalidateDshOverrides(), + ]); + return { profile, status, runtime }; + }), + ); + register( + "dsh:select-profile", + z.object({ name: nonempty.max(64) }).strict(), + ({ name }) => + withDshSetupLock("select-profile", async () => { + const profile = normalizeDshProfile(name); + const info = await inspectDshProfiles(profile); + if (info.activeProfileIssue === "missing") + throw new Error(`DeepSeek Harness profile "${profile}" does not exist.`); + if (info.activeProfileIssue === "non-acp") + throw new Error( + `DeepSeek Harness profile "${profile}" is not an ACP profile.`, + ); + store.state.settings.dshProfile = profile; + dshPlan = null; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + revalidateDshOverrides(), + ]); + return { profile, status, runtime }; + }), + ); + register( + "dsh:desktop-diff", + z.object({ targetProfile: z.string().max(64).optional() }).strict(), + async ({ targetProfile }) => + diffDshDesktopModels(await resolveDshTargetProfile(targetProfile)), + ); + register( + "dsh:dry-run-migrate", + z + .object({ + targetProfile: z.string().max(64).optional(), + selectedIds: z.array(nonempty.max(200)).max(200), + }) + .strict(), + ({ targetProfile, selectedIds }) => + withDshSetupLock( + "dry-run-migrate", + async () => { + const command = await resolveDshCommand(); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before testing Desktop model migration.", + ); + const profile = await resolveDshTargetProfile(targetProfile); + dshPlan = null; + const { plan, ...result } = await dryRunDshMigration(command, profile, selectedIds, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { + strictStdout: true, + allowStaging: true, + }), + }); + if (!plan) return result; + dshPlan = { id: randomUUID(), plan }; + return { ...result, planId: dshPlan.id }; + }, + // Staging never touches the target profile or running workers. + { readOnly: true }, + ), + ); + register( + "dsh:apply-migrate", + z.object({ planId: z.string().min(1).max(100) }).strict(), + ({ planId }) => + withDshSetupLock("apply-migrate", async () => { + // Apply runs exactly what a dry-run verified, at most once. + const verified = dshPlan && dshPlan.id === planId ? dshPlan.plan : null; + dshPlan = null; + if (!verified) + throw new Error( + "Test the selected providers again before importing them.", + ); + const command = await resolveDshCommand(); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before importing Desktop models.", + ); + const applied = await applyDshMigration(command, verified, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { strictStdout: true }), + }); + invalidateHarnessCache("dsh"); + const runtime = await revalidateDshOverrides(); + return { + ok: applied.ok, + targetProfile: verified.targetProfile, + appliedIds: applied.appliedIds, + failed: applied.failed, + models: applied.models, + ...(applied.error ? { error: applied.error } : {}), + ...(applied.restored !== undefined ? { restored: applied.restored } : {}), + runtime, + }; + }), + ); register("connection:guide", z.object({ harness }).strict(), ({ harness }) => host.call("open_worker_setup", { harness }), ); @@ -997,7 +1337,9 @@ export async function createRuntime( }) .strict(), ({ taskId, requestId, response }) => - workers.inputs.respond(taskId, requestId, response), + sharing?.showsRunElsewhere(taskId) + ? sharing.answerWorker(taskId, requestId, response) + : workers.inputs.respond(taskId, requestId, response), ); register("fleet:refresh", identifier, (id) => workers.fleet.refresh(project(id)), @@ -1043,6 +1385,7 @@ export async function createRuntime( speechEndpoint: z.string().max(1000), speech: speechSettingsSchema.optional(), defaultHarness: harness, + dshProfile: z.string().max(64).optional(), model: z.string().max(200), localModel: z.boolean(), maxWorkers: z.number().int().min(1).max(maxWorkerSlots), @@ -1108,15 +1451,31 @@ export async function createRuntime( throw new Error( "Stop active workers before changing runtime settings.", ); + if (dshGate.operation) + throw new Error( + "Another DeepSeek Harness setup operation is already in progress. Wait for it to finish.", + ); // Saving speech, retrieval or worker preferences must not permanently // close the shared engine. Only its executable changes the connection; // reconnect resets the owner lifecycle so the next project can open it. if (settings.memtracePath !== store.state.settings.memtracePath) await engine.reconnect(); + const dshProfile = + settings.dshProfile === undefined + ? store.state.settings.dshProfile + : settings.dshProfile.trim() + ? normalizeDshProfile(settings.dshProfile) + : undefined; + const dshProfileChanged = dshProfile !== store.state.settings.dshProfile; + if (dshProfileChanged) { + invalidateHarnessCache("dsh"); + dshPlan = null; + } // A Settings dialog opened before a worker-default or handoff choice must not erase it. store.state.settings = { ...store.state.settings, ...settings, + dshProfile, speech: settings.speech ?? store.state.settings.speech, contextAssistant: settings.contextAssistant ?? store.state.settings.contextAssistant, @@ -1124,7 +1483,9 @@ export async function createRuntime( handoffAttribution: state().settings.handoffAttribution, }; await changed(); - return store.runtime(); + // New sharing addresses: boards on the old service stop, boards on the new one start. + void sharing?.syncBoards(); + return dshProfileChanged ? revalidateDshOverrides() : store.runtime(); }, ); register("artifact:thumbnail", identifier, async (id) => { @@ -1182,13 +1543,16 @@ export async function createRuntime( registerPlanning(register, state, project, changed); registerOnboarding(register, state, changed); - registerDeletion(register, state, changed); + registerDeletion(register, state, changed, { + forgetSharing: async (projectId) => sharing?.disconnect(projectId), + }); registerCardComments(register, state, changed, (taskId) => { const projectId = taskId ? state().tasks.find((task) => task.id === taskId)?.projectId : state().activeProjectId; return ( (projectId ? team?.identity(projectId) : undefined) ?? + (projectId ? sharing?.author(projectId) : undefined) ?? connections.account.current.principal ); }); @@ -1228,7 +1592,12 @@ export async function createRuntime( ); registerGoalPlanner( register, - new GoalPlanner({ dataDir: store.dir, state, relatedFiles }), + new GoalPlanner({ + dataDir: store.dir, + state, + relatedFiles, + reviewOptions: { dshAdmission: () => dshGate.admit("plan") }, + }), ); registerGoalUpdates( register, @@ -1272,7 +1641,12 @@ export async function createRuntime( () => preview.publishComments(), workers, { - remoteSend: (item, body) => team?.remoteSession(item.id) ? team.sendSessionCommand(item.id, "followup", body) : Promise.resolve(undefined), + remoteSend: (item, body) => { + // A worker a shared project's card shows from another computer gets it through the card's log. + if (sharing?.showsRunElsewhere(item.id)) + return sharing.messageWorker(item.id, body); + return team?.remoteSession(item.id) ? team.sendSessionCommand(item.id, "followup", body) : Promise.resolve(undefined); + }, actor: (item) => team?.sessionActor(item.projectId), edit: async (item, messageId, text, cancel) => { if (!team?.remoteSession(item.id) && !item.messages.some(m => m.id === messageId && m.sourceCommandId)) return false; @@ -1287,7 +1661,9 @@ export async function createRuntime( team?.identity(item.projectId) ?? connections.account.current.principal, reviewProject: (item, parent) => epicAnalysisProject(parent, item), engineVersion: (item) => engine.versionFor(item.id) ?? "Not reported", - reviewer: createReadonlyReviewAgent(store.dir, state), + reviewer: createReadonlyReviewAgent(store.dir, state, { + dshAdmission: () => dshGate.admit("review"), + }), implementationCount: () => workers.implementationCount(), implementationStarting: (taskId) => workers.implementationStarting(taskId), capacityChanged: () => workers.dispatchQueued(), @@ -1338,6 +1714,14 @@ export async function createRuntime( }); const reviewTask = z.object({ taskId: identifier }).strict(); const reviewRun = reviewTask.extend({ runId: identifier }).strict(); + /** A run shown from another computer's card log can be read here, not steered. */ + const refuseRunElsewhere = (taskId: string) => { + if (!sharing?.showsRunElsewhere(taskId)) return; + const owner = task(taskId).sharedSession?.owner; + throw Error( + `This worker runs on ${owner ? `${owner.name}'s ${owner.device}` : "another computer"}. Its code review is run and discussed there.`, + ); + }; const requireReviewLane = (taskId: string) => { if (!isCodeReviewTask(state(), task(taskId))) throw Error( @@ -1345,11 +1729,14 @@ export async function createRuntime( ); }; register("code-review:get", reviewTask, ({ taskId }) => { + if (sharing?.showsRunElsewhere(taskId)) + return task(taskId).sharedSession?.review ?? null; const remote = team?.remoteSession(taskId); return remote ? task(taskId).sharedSession?.review ?? (remote.review ? {...remote.review, taskId} : null) : codeReviews.get(taskId); }); register("code-review:start", reviewTask, async ({ taskId }) => { requireReviewLane(taskId); + refuseRunElsewhere(taskId); const remote = team?.remoteSession(taskId); if (remote) { await team!.sendSessionCommand(taskId, "review-start", "Run code review for this task's recorded changes."); @@ -1392,6 +1779,7 @@ export async function createRuntime( "code-review:discuss", reviewRun.extend({ text: nonempty.max(20000) }).strict(), async ({ taskId, runId, text }) => { + refuseRunElsewhere(taskId); const remote = team?.remoteSession(taskId); if (!remote) return codeReviews.discuss(taskId, runId, text); await team!.sendSessionCommand(taskId, "review-question", text, runId); @@ -1605,6 +1993,16 @@ export async function createRuntime( ); register("preview:hide", z.undefined(), () => preview.hide()); register("worker:changes", identifier, async (id) => { + if (sharing?.showsRunElsewhere(id)) + return ( + (await sharing.sharedChanges(id)) ?? { + taskId: id, + checkpoints: [], + additions: 0, + deletions: 0, + files: 0, + } + ); const item = task(id); let changes = await readDisplayedWorkerChanges(item); if ( @@ -1661,6 +2059,8 @@ export async function createRuntime( if (!team.status(parent.id)) initializeCodeReviewWorkflow(state(), parent.id); await changed(); + // Boards connected on an earlier run take up where they stopped. + void sharing.syncBoards(); const artifactMaintenance = setInterval(() => { void reconcileCatalog().catch((error) => console.error("Artifact catalog check failed:", error), @@ -1747,6 +2147,9 @@ export async function createRuntime( async close() { if (closed) return; closed = true; + // A DeepSeek Harness import holds its only rollback snapshots in memory: + // let it verify or restore the profile before the process exits. + await dshGate.close(); const betaClosing = beta?.close(); clearInterval(artifactMaintenance); await reconcilingArtifacts?.catch((error) => @@ -1758,6 +2161,7 @@ export async function createRuntime( teamIdentity.cancel(); await repositories.close(); await team?.close(); + await sharing?.close(); await speech.close(); await retrieval.close(); await connections.close(); diff --git a/runtime/beta.ts b/runtime/beta.ts index da332b8..4848161 100644 --- a/runtime/beta.ts +++ b/runtime/beta.ts @@ -26,6 +26,13 @@ export interface BetaCredentials extends BetaBinding { signedOut?: boolean; reauthRequired?: boolean; } +/** What memtrace.io checks a session by. It is a credential: show it to memtrace.io only. */ +export interface BetaSessionProof { + refreshToken: string; + deviceId: string; + sessionId: string; + accountId: string; +} export interface BetaStoredState { configured: boolean; signedOut?: boolean; @@ -618,6 +625,32 @@ export class MemCodeBeta { MEMTRACE_ENGINEER: record.account.id, }; } + /** + * The session as memtrace.io's other endpoints check it, once a rotation in + * flight has been saved. Null when there is no session to show. + */ + async sessionProof(): Promise { + await this.initialize(); + // Rotation spends the refresh token, so the old one is refused from then on. + await this.refreshing?.catch(() => {}); + const record = this.record; + if ( + this.changing || + this.closing || + this.signedOut || + !record || + record.signedOut || + record.reauthRequired || + Date.parse(record.refreshExpiresAt) <= this.clock() + ) + return null; + return { + refreshToken: record.refreshToken, + deviceId: record.deviceId, + sessionId: record.sessionId, + accountId: record.account.id, + }; + } clearTelemetryAuthorization() { this.telemetry = undefined; } diff --git a/runtime/browser/engine-choice.ts b/runtime/browser/engine-choice.ts new file mode 100644 index 0000000..6bd8eec --- /dev/null +++ b/runtime/browser/engine-choice.ts @@ -0,0 +1,20 @@ +import { release as osRelease } from "node:os"; +import type { NativeHost } from "../host"; +import type { BrowserEngine } from "./engine"; +import { NativeBrowserPool } from "./native-pool"; +import { HeadlessEngine, WebView2Engine } from "./playwright-engine"; +import { WebKitEngine } from "./webkit-engine"; + +/** Darwin 23 is macOS 14, the first with a WebKit data store per card. */ +const FIRST_NATIVE_DARWIN = 23; + +export function browserEngineFor( + host?: NativeHost, + platform: NodeJS.Platform = process.platform, + release = osRelease(), +): BrowserEngine { + if (host && platform === "win32") return new WebView2Engine(new NativeBrowserPool(host)); + if (host && platform === "darwin" && Number.parseInt(release, 10) >= FIRST_NATIVE_DARWIN) + return new WebKitEngine(host); + return new HeadlessEngine(); +} diff --git a/runtime/browser/engine.ts b/runtime/browser/engine.ts new file mode 100644 index 0000000..40a8053 --- /dev/null +++ b/runtime/browser/engine.ts @@ -0,0 +1,65 @@ +import type { BrowserInteraction, BrowserImage } from "../../src/browser"; + +export type ImageFormat = "png" | "jpeg"; +export type ImageScale = "css" | "device"; +export interface Viewport { + width: number; + height: number; +} +export interface InteractionRequest { + input: BrowserInteraction; + viewport: Viewport; + actor: "user" | "worker"; +} +export interface InteractionFeedback { + cursor?: string; + point?: { x: number; y: number }; +} +export interface CaptureRequest { + scale: ImageScale; + format: ImageFormat; + /** The card's own viewport, for engines that cannot ask the page. */ + viewport: Viewport; + density: number; +} +export interface SurfacePlacement { + visible: boolean; + bounds?: { x: number; y: number; width: number; height: number }; +} + +/** One tab of a card's browser, whichever engine draws it. */ +export interface BrowserPage { + url(): string; + title(): Promise; + isClosed(): boolean; + goto(url: string): Promise; + /** The worker's text view: control refs plus the accessibility tree. */ + inspect(): Promise; + onNavigated(listener: () => void): void; + onLoaded(listener: () => void): void; + onClosed(listener: () => void): void; +} + +/** A card's browser: its own storage, its tabs and the popups they open. */ +export interface BrowserTabs { + /** Brings page state up to date for engines that have to ask for it. */ + sync(): Promise; + newPage(): Promise; + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void): void; + interact(page: BrowserPage, request: InteractionRequest): Promise; + capture(page: BrowserPage, request: CaptureRequest): Promise; + resize(page: BrowserPage, viewport: Viewport, density: number): Promise; + closePage(page: BrowserPage): Promise; + close(): Promise; +} + +/** Where card browsers live: hidden Chrome frames or a native surface over the card. */ +export interface BrowserEngine { + /** True when the human sees a live native surface instead of frames. */ + readonly native: boolean; + connected(): boolean; + open(viewport: Viewport, density: number, taskId: string): Promise; + /** Places, shows or hides the native surface over the card; frame engines ignore it. */ + surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement): Promise; + close(): Promise; +} diff --git a/runtime/browser/manager.ts b/runtime/browser/manager.ts index 7811d07..9dcac2c 100644 --- a/runtime/browser/manager.ts +++ b/runtime/browser/manager.ts @@ -1,7 +1,6 @@ import { randomUUID } from "node:crypto"; import { mkdir, writeFile, appendFile } from "node:fs/promises"; import { join } from "node:path"; -import type { Page } from "playwright-core"; import type { AppState } from "../../src/shared"; import { browserURL, @@ -11,17 +10,20 @@ import { type WorkerBrowserState, } from "../../src/browser"; import { within, now } from "../local"; -import { BrowserPool, type BrowserSession } from "./pool"; -import { NativeBrowserPool } from "./native-pool"; import type { NativeHost } from "../host"; -import { inspectPage, interact } from "./inspect"; -import { BrowserRendering } from "./render"; import { browserDeadline } from "./capture"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + ImageFormat, +} from "./engine"; +import { browserEngineFor } from "./engine-choice"; interface Session { state: WorkerBrowserState; - context?: BrowserSession; - pages: Map; + context?: BrowserTabs; + pages: Map; selected?: string; queue: Promise; revision: number; @@ -32,20 +34,14 @@ interface Session { export class AgentBrowserManager { private closing = false; private sessions = new Map(); - private pool: BrowserPool | NativeBrowserPool; - private rendering = new BrowserRendering(); constructor( private state: () => AppState, private dataDir: string, private changed: () => Promise, private maxContexts = 16, host?: NativeHost, - ) { - this.pool = - host && process.platform === "win32" - ? new NativeBrowserPool(host) - : new BrowserPool(); - } + private engine: BrowserEngine = browserEngineFor(host), + ) {} private session(taskId: string): Session { if (!this.state().tasks.some((task) => task.id === taskId)) throw Error("Work item not found."); @@ -61,7 +57,7 @@ export class AgentBrowserManager { activity: [], viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1, - nativeSurface: this.pool.native, + nativeSurface: this.engine.native, }, pages: new Map(), queue: Promise.resolve(), @@ -112,7 +108,11 @@ export class AgentBrowserManager { })); return structuredClone(session.state); } - private register(session: Session, page: Page, replaces?: Page): string { + private register( + session: Session, + page: BrowserPage, + replaces?: BrowserPage, + ): string { const previous = [...session.pages].find( ([, existing]) => existing === page, ); @@ -137,9 +137,9 @@ export class AgentBrowserManager { }) .catch(() => {}); }; - page.on("domcontentloaded", update); - page.on("framenavigated", (frame) => { - if (frame !== page.mainFrame() || session.pages.get(id) !== page) return; + page.onLoaded(update); + page.onNavigated(() => { + if (session.pages.get(id) !== page) return; session.revision++; session.observed = undefined; update(); @@ -147,15 +147,7 @@ export class AgentBrowserManager { () => {}, ); }); - if (!this.pool.native) - page.on("popup", (popup) => this.register(session, popup)); - page.on("dialog", (dialog) => { - void dialog.dismiss(); - }); - page.on("download", (download) => { - void download.cancel(); - }); - page.on("close", () => { + page.onClosed(() => { if (session.pages.get(id) !== page) return; session.pages.delete(id); if (session.selected === id) @@ -171,11 +163,11 @@ export class AgentBrowserManager { update(); return id; } - private async context(session: Session): Promise { - if (session.context && this.pool.connected()) return session.context; + private async context(session: Session): Promise { + if (session.context && this.engine.connected()) return session.context; const occupied = [...this.sessions.values()].filter( (other) => - (other.context && this.pool.connected()) || + (other.context && this.engine.connected()) || other.state.status === "starting", ); if (occupied.length >= this.maxContexts) { @@ -202,27 +194,19 @@ export class AgentBrowserManager { ); } session.state.status = "starting"; - session.context = await this.pool.context( + session.context = await this.engine.open( session.state.viewport, session.state.deviceScaleFactor, session.state.taskId, ); - await session.context.route("**/*", async (route) => { - try { - browserURL(route.request().url()); - await route.continue(); - } catch { - await route.abort("blockedbyclient"); - } - }); - session.context.onPage?.((page, replaces) => + session.context.onPage((page, replaces) => this.register(session, page, replaces), ); session.pages.clear(); session.selected = undefined; return session.context; } - private page(session: Session, tabId?: string): Page { + private page(session: Session, tabId?: string): BrowserPage { const page = session.pages.get(tabId ?? session.selected ?? ""); if (!page || page.isClosed()) throw Error("Open a browser tab in this work item first."); @@ -266,6 +250,7 @@ export class AgentBrowserManager { request: BrowserRequest, actor: "user" | "worker", ): Promise { + await session.context?.sync(); const observing = ["state", "frame", "observe"].includes(request.action); if (actor === "worker" && !observing && session.state.control === "user") throw Error( @@ -285,11 +270,11 @@ export class AgentBrowserManager { : "Browser returned to the worker.", ); } else if (request.action === "surface") { - if (this.pool instanceof NativeBrowserPool) { + if (this.engine.native) { const page = request.tabId ? this.page(session, request.tabId) : undefined; - await this.pool.surface(session.state.taskId, page, { + await this.engine.surface(session.state.taskId, page, { visible: request.visible, bounds: request.bounds, }); @@ -321,11 +306,7 @@ export class AgentBrowserManager { : (existing?.[1] ?? (await context.newPage())); const id = request.tabId ?? existing?.[0] ?? this.register(session, page); session.selected = id; - if (!existing) - await page.goto(url.href, { - waitUntil: "domcontentloaded", - timeout: 20000, - }); + if (!existing) await page.goto(url.href); session.state.status = "ready"; this.view(session); session.state.tabs.find((tab) => tab.id === id)!.title = @@ -365,9 +346,7 @@ export class AgentBrowserManager { session.state.pointer = undefined; session.state.cursor = undefined; } else if (command.action === "close") { - if (this.pool instanceof NativeBrowserPool) - await this.pool.closePage(session.state.taskId, page); - else await page.close(); + await session.context!.closePage(page); if (!session.pages.size) { await session.context?.close(); session.context = undefined; @@ -375,17 +354,11 @@ export class AgentBrowserManager { } } else { session.state.action = command.action; - const native = - this.pool instanceof NativeBrowserPool ? this.pool : undefined; - if (native && actor === "worker") - await native.busy(session.state.taskId, page, true); - let feedback; - try { - feedback = await interact(page, command, session.state.viewport); - } finally { - if (native && actor === "worker") - await native.busy(session.state.taskId, page, false); - } + const feedback = await session.context!.interact(page, { + input: command, + viewport: session.state.viewport, + actor, + }); if ( feedback.cursor && page === session.pages.get(session.selected ?? "") @@ -410,9 +383,8 @@ export class AgentBrowserManager { session.state.viewport = { width: request.width, height: request.height }; session.state.deviceScaleFactor = request.deviceScaleFactor ?? session.state.deviceScaleFactor; - for (const page of this.pool.native ? [] : session.pages.values()) - await this.rendering.resize( - session.context!, + for (const page of session.pages.values()) + await session.context!.resize( page, session.state.viewport, session.state.deviceScaleFactor, @@ -425,7 +397,7 @@ export class AgentBrowserManager { if (actor === "worker" && session.state.control === "worker") session.selected = tabId; const text = await browserDeadline( - inspectPage(page), + page.inspect(), 10000, "Browser DOM observation", ); @@ -459,7 +431,7 @@ export class AgentBrowserManager { return { state: this.view(session), ...(page && page.url() !== "about:blank" - ? { image: await this.image(session, page, "device") } + ? { image: await this.image(session, page, "device", "jpeg") } : {}), }; } else if (request.action === "capture") @@ -467,42 +439,18 @@ export class AgentBrowserManager { session.state.action = undefined; return { state: this.view(session) }; } - private async image(session: Session, page: Page, scale: "css" | "device") { - const actual = this.pool.native - ? await browserDeadline( - page.evaluate(() => ({ - viewport: { width: innerWidth, height: innerHeight }, - density: devicePixelRatio, - })), - 3000, - "Browser viewport observation", - ) - : undefined; - const data = - this.pool instanceof NativeBrowserPool - ? await this.pool.capture( - session.state.taskId, - page, - scale, - actual!.viewport, - actual!.density, - ) - : await browserDeadline( - this.rendering.capture( - session.context!, - page, - actual?.viewport ?? session.state.viewport, - actual?.density ?? session.state.deviceScaleFactor, - scale, - ), - 10000, - "Browser screenshot", - ); - return { - mimeType: "image/png" as const, - data, - ...(actual?.viewport ?? session.state.viewport), - }; + private image( + session: Session, + page: BrowserPage, + scale: "css" | "device", + format: ImageFormat = "png", + ) { + return session.context!.capture(page, { + scale, + format, + viewport: session.state.viewport, + density: session.state.deviceScaleFactor, + }); } private async capture( session: Session, @@ -538,7 +486,7 @@ export class AgentBrowserManager { async close(): Promise { this.closing = true; // Closing Chromium cancels pending navigation and screenshot operations. - await this.pool.close(); + await this.engine.close(); await Promise.allSettled( [...this.sessions.values()].map((session) => session.queue), ); diff --git a/runtime/browser/playwright-engine.ts b/runtime/browser/playwright-engine.ts new file mode 100644 index 0000000..75e54a6 --- /dev/null +++ b/runtime/browser/playwright-engine.ts @@ -0,0 +1,239 @@ +import type { Page, Route } from "playwright-core"; +import { browserURL, type BrowserImage } from "../../src/browser"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + CaptureRequest, + InteractionFeedback, + InteractionRequest, + SurfacePlacement, + Viewport, +} from "./engine"; +import { BrowserPool, type BrowserSession } from "./pool"; +import type { NativeBrowserPool } from "./native-pool"; +import { inspectPage, interact } from "./inspect"; +import { BrowserRendering } from "./render"; +import { browserDeadline } from "./capture"; + +/** A tab Playwright drives: headless Chrome, or WebView2 over CDP. */ +export class PlaywrightPage implements BrowserPage { + constructor(readonly raw: Page) { + raw.on("dialog", (dialog) => { + void dialog.dismiss(); + }); + raw.on("download", (download) => { + void download.cancel(); + }); + } + url() { + return this.raw.url(); + } + title() { + return this.raw.title(); + } + isClosed() { + return this.raw.isClosed(); + } + async goto(url: string) { + await this.raw.goto(url, { waitUntil: "domcontentloaded", timeout: 20000 }); + } + inspect() { + return inspectPage(this.raw); + } + onNavigated(listener: () => void) { + this.raw.on("framenavigated", (frame) => { + if (frame === this.raw.mainFrame()) listener(); + }); + } + onLoaded(listener: () => void) { + this.raw.on("domcontentloaded", () => listener()); + } + onClosed(listener: () => void) { + this.raw.on("close", () => listener()); + } +} + +function playwrightPage(page: BrowserPage): Page { + return (page as PlaywrightPage).raw; +} + +async function allowBrowserAddresses(route: Route) { + try { + browserURL(route.request().url()); + await route.continue(); + } catch { + await route.abort("blockedbyclient"); + } +} + +abstract class PlaywrightTabs implements BrowserTabs { + private wrapped = new WeakMap(); + private listener?: (page: BrowserPage, replaces?: BrowserPage) => void; + constructor(protected session: BrowserSession) { + session.onPage?.((page, replaces) => + this.listener?.(this.wrap(page), replaces && this.wrap(replaces)), + ); + } + protected wrap(page: Page): PlaywrightPage { + let wrapped = this.wrapped.get(page); + if (!wrapped) { + wrapped = new PlaywrightPage(page); + this.wrapped.set(page, wrapped); + this.adopted(page); + } + return wrapped; + } + /** Called once for every tab, including popups. */ + protected adopted(_page: Page) {} + protected announce(page: Page) { + this.listener?.(this.wrap(page)); + } + /** Playwright reports page changes as events, so there is nothing to fetch. */ + async sync() {} + allowOnlyBrowserAddresses() { + return this.session.route("**/*", allowBrowserAddresses); + } + async newPage() { + return this.wrap(await this.session.newPage()); + } + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void) { + this.listener = listener; + } + close() { + return this.session.close(); + } + abstract interact( + page: BrowserPage, + request: InteractionRequest, + ): Promise; + abstract capture(page: BrowserPage, request: CaptureRequest): Promise; + abstract resize(page: BrowserPage, viewport: Viewport, density: number): Promise; + abstract closePage(page: BrowserPage): Promise; +} + +class HeadlessTabs extends PlaywrightTabs { + constructor( + session: BrowserSession, + private rendering: BrowserRendering, + ) { + super(session); + } + protected adopted(page: Page) { + page.on("popup", (popup) => this.announce(popup)); + } + interact(page: BrowserPage, request: InteractionRequest) { + return interact(playwrightPage(page), request.input, request.viewport); + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const data = await browserDeadline( + this.rendering.capture( + this.session, + playwrightPage(page), + request.viewport, + request.density, + request.scale, + request.format, + ), + 10000, + "Browser screenshot", + ); + return { mimeType: `image/${request.format}`, data, ...request.viewport }; + } + resize(page: BrowserPage, viewport: Viewport, density: number) { + return this.rendering.resize(this.session, playwrightPage(page), viewport, density); + } + closePage(page: BrowserPage) { + return playwrightPage(page).close(); + } +} + +/** Cards share one hidden Chrome; the human sees its frames. */ +export class HeadlessEngine implements BrowserEngine { + readonly native = false; + private rendering = new BrowserRendering(); + constructor(private pool = new BrowserPool()) {} + connected() { + return this.pool.connected(); + } + async open(viewport: Viewport, density: number, taskId: string) { + const tabs = new HeadlessTabs( + await this.pool.context(viewport, density, taskId), + this.rendering, + ); + await tabs.allowOnlyBrowserAddresses(); + return tabs; + } + async surface(_taskId: string, _page: BrowserPage | undefined, _placement: SurfacePlacement) {} + close() { + return this.pool.close(); + } +} + +class WebView2Tabs extends PlaywrightTabs { + constructor( + session: BrowserSession, + private pool: NativeBrowserPool, + private taskId: string, + ) { + super(session); + } + async interact(page: BrowserPage, request: InteractionRequest) { + const raw = playwrightPage(page), + worker = request.actor === "worker"; + if (worker) await this.pool.busy(this.taskId, raw, true); + try { + return await interact(raw, request.input, request.viewport); + } finally { + if (worker) await this.pool.busy(this.taskId, raw, false); + } + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const raw = playwrightPage(page); + const actual = await browserDeadline( + raw.evaluate(() => ({ + viewport: { width: innerWidth, height: innerHeight }, + density: devicePixelRatio, + })), + 3000, + "Browser viewport observation", + ); + // The native WebView2 capture is always PNG; only Chrome's frames change. + const data = await this.pool.capture( + this.taskId, + raw, + request.scale, + actual.viewport, + actual.density, + ); + return { mimeType: "image/png", data, ...actual.viewport }; + } + async resize() {} + closePage(page: BrowserPage) { + return this.pool.closePage(this.taskId, playwrightPage(page)); + } +} + +/** Windows: each card's tab is a WebView2 over the card that Playwright drives over CDP. */ +export class WebView2Engine implements BrowserEngine { + readonly native = true; + constructor(private pool: NativeBrowserPool) {} + connected() { + return this.pool.connected(); + } + async open(viewport: Viewport, density: number, taskId: string) { + const tabs = new WebView2Tabs( + await this.pool.context(viewport, density, taskId), + this.pool, + taskId, + ); + await tabs.allowOnlyBrowserAddresses(); + return tabs; + } + surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement) { + return this.pool.surface(taskId, page && playwrightPage(page), { ...placement }); + } + close() { + return this.pool.close(); + } +} diff --git a/runtime/browser/render.ts b/runtime/browser/render.ts index 41c1b57..2806550 100644 --- a/runtime/browser/render.ts +++ b/runtime/browser/render.ts @@ -1,5 +1,10 @@ import type { CDPSession, Page } from "playwright-core"; import type { BrowserSession } from "./pool"; +import type { ImageFormat } from "./engine"; + +// At Retina density Chrome encodes this 2-3x faster than PNG at about a third +// of the size; 90 approaches PNG size on text-heavy pages. +const JPEG_QUALITY = 85; export class BrowserRendering { private sessions = new WeakMap(); @@ -31,18 +36,24 @@ export class BrowserRendering { viewport: { width: number; height: number }, deviceScaleFactor: number, scale: "css" | "device", + format: ImageFormat = "png", ): Promise { const session = await this.session(context, page); // Capture the compositor at its actual density. Playwright's screenshot // helper otherwise rescales using the context's original density after a // display change. CDP also preserves the page's native caret and selection. + // The clip is in page coordinates, so it starts where the page is scrolled. + const { cssVisualViewport: visible } = await session.send( + "Page.getLayoutMetrics", + ); const result = await session.send("Page.captureScreenshot", { - format: "png", + format, + ...(format === "jpeg" ? { quality: JPEG_QUALITY } : {}), fromSurface: true, captureBeyondViewport: false, clip: { - x: 0, - y: 0, + x: visible.pageX, + y: visible.pageY, ...viewport, scale: scale === "css" ? 1 / deviceScaleFactor : 1, }, diff --git a/runtime/browser/webkit-accessibility.ts b/runtime/browser/webkit-accessibility.ts new file mode 100644 index 0000000..9d2a40c --- /dev/null +++ b/runtime/browser/webkit-accessibility.ts @@ -0,0 +1,174 @@ +/** + * The page's accessibility tree for a worker, written like Playwright's aria + * snapshot (`- role "name" [state]: value`) so observations read the same on + * every platform. Runs as an async function body in MemCode's content world. + */ +export const ACCESSIBILITY_TREE = ` +const MAX_LINES = 500, MAX_NODES = 6000, MAX_TEXT = 160; +const SKIPPED = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "META", "LINK"]); +const FROM_CONTENT = new Set(["button", "link", "heading", "option", "tab", "menuitem", "cell", "columnheader", "rowheader", "treeitem", "checkbox", "radio", "switch"]); +const TEXT_LEAF = new Set(["listitem", "paragraph", "cell", "columnheader", "rowheader", "status", "caption", "blockquote", "code", "term", "definition"]); +const VALUED = new Set(["textbox", "searchbox", "spinbutton", "slider", "combobox"]); +const lines = []; +let visited = 0; +const clean = (text) => (text || "").replace(/\\s+/g, " ").trim(); +const clip = (text) => (text.length > MAX_TEXT ? text.slice(0, MAX_TEXT - 1) + "…" : text); +const quote = (text) => JSON.stringify(clip(text)); + +function hidden(element) { + if (element.hidden || element.getAttribute("aria-hidden") === "true") return true; + const style = getComputedStyle(element); + return style.display === "none" || style.visibility === "hidden"; +} + +function inputRole(element) { + const type = (element.getAttribute("type") || "text").toLowerCase(); + if (type === "hidden") return ""; + if (["button", "submit", "reset", "image"].includes(type)) return "button"; + if (type === "checkbox") return element.getAttribute("role") === "switch" ? "switch" : "checkbox"; + if (type === "radio") return "radio"; + if (type === "range") return "slider"; + if (type === "number") return "spinbutton"; + if (type === "search") return "searchbox"; + return element.list ? "combobox" : "textbox"; +} + +function role(element) { + const explicit = clean(element.getAttribute("role")).split(" ")[0]; + if (explicit && explicit !== "presentation" && explicit !== "none") return explicit; + if (explicit) return ""; + const tag = element.tagName; + if (/^H[1-6]$/.test(tag)) return "heading"; + switch (tag) { + case "A": return element.hasAttribute("href") ? "link" : ""; + case "BUTTON": case "SUMMARY": return "button"; + case "INPUT": return inputRole(element); + case "TEXTAREA": return "textbox"; + case "SELECT": return element.multiple || element.size > 1 ? "listbox" : "combobox"; + case "OPTION": return "option"; + case "IMG": return element.getAttribute("alt") === "" ? "" : "img"; + case "UL": case "OL": case "MENU": return "list"; + case "LI": return "listitem"; + case "NAV": return "navigation"; + case "MAIN": return "main"; + case "ASIDE": return "complementary"; + case "HEADER": return element.closest("article, section, main") ? "" : "banner"; + case "FOOTER": return element.closest("article, section, main") ? "" : "contentinfo"; + case "FORM": return element.getAttribute("aria-label") || element.getAttribute("name") ? "form" : ""; + case "TABLE": return "table"; + case "TR": return "row"; + case "TH": return "columnheader"; + case "TD": return "cell"; + case "DIALOG": return "dialog"; + case "P": return "paragraph"; + case "OUTPUT": return "status"; + case "PROGRESS": return "progressbar"; + case "IFRAME": return "iframe"; + case "BLOCKQUOTE": return "blockquote"; + case "CODE": return "code"; + case "DT": return "term"; + case "DD": return "definition"; + case "FIGCAPTION": case "CAPTION": return "caption"; + } + return ""; +} + +function visibleText(node) { + if (node.nodeType === Node.TEXT_NODE) return node.textContent; + if (node.nodeType !== Node.ELEMENT_NODE || SKIPPED.has(node.tagName) || hidden(node)) return ""; + if (node.tagName === "IMG") return node.getAttribute("alt") || ""; + return [...node.childNodes].map(visibleText).join(node.tagName === "BR" ? " " : ""); +} + +function labelOf(element) { + if (element.labels && element.labels.length) + return clean([...element.labels].map((label) => + [...label.childNodes].filter((child) => child !== element && !(child.contains && child.contains(element))).map(visibleText).join(" ")).join(" ")); + return ""; +} + +function name(element, kind) { + const labelledBy = clean(element.getAttribute("aria-labelledby")); + if (labelledBy) { + const text = clean(labelledBy.split(" ").map((id) => { const target = document.getElementById(id); return target ? visibleText(target) : ""; }).join(" ")); + if (text) return text; + } + const label = clean(element.getAttribute("aria-label")); + if (label) return label; + if (["INPUT", "TEXTAREA", "SELECT", "METER", "PROGRESS"].includes(element.tagName)) { + const labelled = labelOf(element); + if (labelled) return labelled; + } + if (element.tagName === "IMG") return clean(element.getAttribute("alt") || element.getAttribute("title")); + if (element.tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) + return clean(element.value || (element.type === "submit" ? "Submit" : "")); + if (element.tagName === "IFRAME") return clean(element.getAttribute("title")); + if (FROM_CONTENT.has(kind)) { + const text = clean(element.tagName === "OPTION" ? element.label : visibleText(element)); + if (text) return text; + } + return clean(element.getAttribute("title") || element.getAttribute("placeholder")); +} + +function states(element, kind) { + const flags = []; + if (kind === "heading") flags.push("level=" + (element.getAttribute("aria-level") || element.tagName.slice(1))); + const checked = element.getAttribute("aria-checked"); + if (checked === "true" || (checked === null && element.checked)) flags.push("checked"); + if (checked === "mixed" || element.indeterminate) flags.push("checked=mixed"); + if (element.getAttribute("aria-selected") === "true" || (kind === "option" && element.selected)) flags.push("selected"); + if (element.getAttribute("aria-expanded")) flags.push("expanded=" + element.getAttribute("aria-expanded")); + if (element.getAttribute("aria-pressed") === "true") flags.push("pressed"); + if (element.disabled || element.getAttribute("aria-disabled") === "true") flags.push("disabled"); + return flags.map((flag) => " [" + flag + "]").join(""); +} + +function value(element, kind) { + if (!VALUED.has(kind)) return ""; + if (element.tagName === "SELECT") return ""; + if ("value" in element) return clean(element.value); + return clean(element.textContent); +} + +function emit(depth, text) { + if (lines.length < MAX_LINES) lines.push(" ".repeat(depth) + "- " + text); +} + +/** Element and text children as they will be shown, flattening unnamed containers. */ +function walk(node, depth) { + if (lines.length >= MAX_LINES || ++visited > MAX_NODES) return; + if (node.nodeType === Node.TEXT_NODE) { + const text = clean(node.textContent); + if (text) emit(depth, "text: " + clip(text)); + return; + } + if (node.nodeType !== Node.ELEMENT_NODE || SKIPPED.has(node.tagName) || hidden(node)) return; + const kind = role(node); + if (!kind) { + for (const child of node.childNodes) walk(child, depth); + return; + } + const label = name(node, kind); + const head = kind + (label ? " " + quote(label) : "") + states(node, kind); + const shown = value(node, kind); + if (shown) return emit(depth, head + ": " + clip(shown)); + if (FROM_CONTENT.has(kind) && !hasRoles(node)) return emit(depth, head); + if (TEXT_LEAF.has(kind) && !hasRoles(node)) { + const text = clean(visibleText(node)); + return emit(depth, text ? head + ": " + clip(text) : head); + } + const before = lines.length; + emit(depth, head + ":"); + for (const child of node.childNodes) walk(child, depth + 1); + if (lines.length === before + 1) lines[before] = lines[before].slice(0, -1); +} + +function hasRoles(element) { + for (const child of element.querySelectorAll("*")) if (role(child) && !hidden(child)) return true; + return false; +} + +walk(document.body, 0); +if (lines.length >= MAX_LINES || visited > MAX_NODES) lines.push("- …"); +return lines.join("\\n"); +`; diff --git a/runtime/browser/webkit-driver.ts b/runtime/browser/webkit-driver.ts new file mode 100644 index 0000000..d337f91 --- /dev/null +++ b/runtime/browser/webkit-driver.ts @@ -0,0 +1,318 @@ +import type { BrowserInteraction } from "../../src/browser"; +import type { InteractionFeedback, InteractionRequest, Viewport } from "./engine"; +import { ACCESSIBILITY_TREE } from "./webkit-accessibility"; + +export type NativeInput = + | { kind: "click" | "move"; x: number; y: number } + | { kind: "wheel"; x: number; y: number; deltaY: number } + | { kind: "key"; key: string } + | { kind: "text"; text: string }; + +/** What the WebKit driver needs from one native tab. */ +export interface NativeScripts { + url(): string; + title(): Promise; + /** Runs an async function body in MemCode's content world; it returns text. */ + run(script: string): Promise; + input(input: NativeInput): Promise; + travel(action: "back" | "forward" | "reload"): Promise; +} + +type Point = { x: number; y: number }; +type Echo = "mouseup" | "mousemove" | "keyup" | "input" | "wheel"; + +const MAX_OBSERVATION = 18000; +const ECHO_TIMEOUT_MS = 1500; +const ECHO_POLL_MS = 15; +const SETTLE_TIMEOUT_MS = 8000; +const SETTLE_POLL_MS = 100; +const DEFAULT_SCROLL = 600; +const KNOWN_CURSORS = [ + "default", + "auto", + "pointer", + "text", + "crosshair", + "grab", + "grabbing", + "not-allowed", + "wait", + "progress", +]; + +/** Same refs and wording as `inspectPage`, so a worker sees one format everywhere. */ +const TAG_CONTROLS = ` +for (const node of document.querySelectorAll("[data-memcode-ref]")) + node.removeAttribute("data-memcode-ref"); +const nodes = [...document.querySelectorAll( + "a,button,input,textarea,select,[role=button],[contenteditable=true]", +)] + .filter((node) => node.getClientRects().length && getComputedStyle(node).visibility !== "hidden") + .slice(0, 100); +return nodes + .map((node, index) => { + const ref = "m" + (index + 1); + node.setAttribute("data-memcode-ref", ref); + return (ref + ": " + node.tagName.toLowerCase() + " " + (node.getAttribute("aria-label") || node.innerText || node.getAttribute("placeholder") || node.getAttribute("name") || "")).slice(0, 220); + }) + .join("\\n"); +`; + +/** + * Counts the trusted events the page has received, per type. A fresh document + * starts a fresh count, which tells the driver the page moved on. + */ +const ECHO_COUNTER = ` +const fresh = !globalThis.__memcodeEchoes; +const echoes = (globalThis.__memcodeEchoes ??= (() => { + const seen = { mouseup: 0, mousemove: 0, keyup: 0, input: 0, wheel: 0 }; + for (const type of Object.keys(seen)) + addEventListener(type, (event) => { if (event.isTrusted) seen[type]++; }, { capture: true, passive: true }); + return seen; +})()); +`; + +/** Controls WebKit answers with an AppKit menu or panel instead of the page. */ +const PICKER_CHECK = ` +const pickers = { file: "Choosing files needs the user: ask them to pick the file.", + date: "Set dates with type instead of the picker.", "datetime-local": "Set dates with type instead of the picker.", + month: "Set dates with type instead of the picker.", week: "Set dates with type instead of the picker.", + time: "Set times with type instead of the picker.", color: "Set colors with type instead of the picker." }; +const refusal = (element) => { + const control = element && element.closest ? element.closest("select, input") : null; + if (!control) return undefined; + if (control.tagName === "SELECT") + return "Use choose with a control ref and option value or label for an HTML select."; + return pickers[(control.getAttribute("type") || "").toLowerCase()]; +}; +`; + +function script(body: string, args: Record = {}) { + return `const args = ${JSON.stringify(args)};\n${body}`; +} + +async function runJson(page: NativeScripts, body: string, args: Record = {}) { + return JSON.parse(await page.run(script(body, args))) as T; +} + +function failure(result: { error?: string }) { + if (result.error) throw Error(result.error); +} + +export async function inspectNativePage(page: NativeScripts): Promise { + const references = await page.run(TAG_CONTROLS); + const accessible = await page + .run(ACCESSIBILITY_TREE) + .catch(() => "Accessibility snapshot unavailable."); + return `URL: ${page.url()}\nTitle: ${await page.title()}\n\nVisible controls (use ref for actions):\n${references}\n\nAccessibility:\n${accessible}`.slice( + 0, + MAX_OBSERVATION, + ); +} + +/** Delivers one input and waits until the page has seen it, or a new page loaded. */ +async function deliver(page: NativeScripts, input: NativeInput, echo: Echo) { + const before = await runJson<{ count: number }>( + page, + `${ECHO_COUNTER} return JSON.stringify({ count: echoes[args.echo] });`, + { echo }, + ); + await page.input(input); + const deadline = Date.now() + ECHO_TIMEOUT_MS; + while (Date.now() < deadline) { + const after = await runJson<{ count: number; fresh: boolean }>( + page, + `${ECHO_COUNTER} return JSON.stringify({ count: echoes[args.echo], fresh });`, + { echo }, + ).catch(() => ({ count: before.count, fresh: true })); + if (after.fresh || after.count > before.count) return; + await new Promise((resolve) => setTimeout(resolve, ECHO_POLL_MS)); + } +} + +/** Scrolls a control into view and finds a point on it that receives the click. */ +async function target(page: NativeScripts, ref: string): Promise { + const deadline = Date.now() + SETTLE_TIMEOUT_MS; + for (;;) { + const found = await runJson( + page, + `${PICKER_CHECK} + const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + const refused = refusal(element); + if (refused) return JSON.stringify({ error: refused }); + const view = () => element.getBoundingClientRect(); + let rect = view(); + if (rect.top < 0 || rect.left < 0 || rect.bottom > innerHeight || rect.right > innerWidth) { + element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); + await new Promise((resolve) => setTimeout(resolve, 50)); + rect = view(); + } + if (!rect.width || !rect.height || getComputedStyle(element).visibility === "hidden") + return JSON.stringify({ retry: true, error: "That control is not visible." }); + if (element.disabled) return JSON.stringify({ retry: true, error: "That control is disabled." }); + const x = Math.min(Math.max(rect.left + rect.width / 2, 0), innerWidth - 1); + const y = Math.min(Math.max(rect.top + rect.height / 2, 0), innerHeight - 1); + const hit = document.elementFromPoint(x, y); + const receives = hit && (hit === element || element.contains(hit) || (hit.control === element)); + if (!receives) { + const cover = hit ? hit.tagName.toLowerCase() + (hit.id ? "#" + hit.id : "") : "nothing"; + return JSON.stringify({ retry: true, error: "Another element (" + cover + ") covers that control. Close it or observe again." }); + } + return JSON.stringify({ x, y });`, + { ref }, + ); + if (!found.error) return { x: found.x, y: found.y }; + if (!found.retry || Date.now() > deadline) failure(found); + await new Promise((resolve) => setTimeout(resolve, SETTLE_POLL_MS)); + } +} + +async function refusePickerAt(page: NativeScripts, point: Point) { + failure( + await runJson<{ error?: string }>( + page, + `${PICKER_CHECK} return JSON.stringify({ error: refusal(document.elementFromPoint(args.x, args.y)) });`, + point, + ), + ); +} + +function inside(point: Point | undefined, viewport: Viewport): point is Point { + return !!point && point.x <= viewport.width && point.y <= viewport.height; +} + +function pointOf(input: BrowserInteraction): Point | undefined { + return input.x !== undefined && input.y !== undefined ? { x: input.x, y: input.y } : undefined; +} + +async function click(page: NativeScripts, input: BrowserInteraction, viewport: Viewport) { + let point = pointOf(input); + if (input.ref) point = await target(page, input.ref); + else if (!inside(point, viewport)) + throw Error("Choose a current control ref or a point inside this page."); + else await refusePickerAt(page, point); + await deliver(page, { kind: "click", ...point! }, "mouseup"); + return point; +} + +/** Focuses the field and selects what is in it, so typing replaces it like Playwright's fill. */ +async function type(page: NativeScripts, input: BrowserInteraction) { + if (input.text === undefined) throw Error("Text is required."); + if (!input.ref) { + if (input.text) await deliver(page, { kind: "text", text: input.text }, "input"); + return; + } + const field = await runJson<{ error?: string; set?: boolean; empty?: boolean }>( + page, + `const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + const kind = (element.getAttribute("type") || "").toLowerCase(); + const picked = ["date", "datetime-local", "month", "week", "time", "color", "range"].includes(kind); + if (element.tagName === "INPUT" && picked) { + element.focus(); + element.value = args.text; + element.dispatchEvent(new Event("input", { bubbles: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return JSON.stringify({ set: true }); + } + const editable = element.isContentEditable || ["INPUT", "TEXTAREA"].includes(element.tagName); + if (!editable) return JSON.stringify({ error: "That control does not take text." }); + if (element.disabled || element.readOnly) return JSON.stringify({ error: "That field is read-only." }); + element.scrollIntoView({ block: "center", behavior: "instant" }); + element.focus(); + if (element.isContentEditable) { + const range = document.createRange(); + range.selectNodeContents(element); + getSelection().removeAllRanges(); + getSelection().addRange(range); + return JSON.stringify({ empty: !element.textContent }); + } + try { element.select(); } catch {} + return JSON.stringify({ empty: !element.value });`, + { ref: input.ref, text: input.text }, + ); + failure(field); + if (field.set) return; + if (input.text) await deliver(page, { kind: "text", text: input.text }, "input"); + else if (!field.empty) await deliver(page, { kind: "key", key: "Backspace" }, "keyup"); +} + +/** As Playwright's selectOption: sets the option and fires input and change. */ +async function choose(page: NativeScripts, input: BrowserInteraction) { + if (!input.ref || (input.value === undefined && input.label === undefined)) + throw Error("Choose a current select ref and option value or label."); + failure( + await runJson<{ error?: string }>( + page, + `const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + if (element.tagName !== "SELECT") return JSON.stringify({ error: "Choose works on an HTML select." }); + const option = [...element.options].find((option) => + args.value !== null ? option.value === args.value : option.label === args.label || option.textContent.trim() === args.label); + if (!option) return JSON.stringify({ error: "That select has no such option." }); + if (option.disabled) return JSON.stringify({ error: "That option is disabled." }); + element.value = option.value; + element.dispatchEvent(new Event("input", { bubbles: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return JSON.stringify({});`, + { ref: input.ref, value: input.value ?? null, label: input.label ?? null }, + ), + ); +} + +async function cursorAt(page: NativeScripts, point: Point) { + const cursor = await page + .run( + script( + `const element = document.elementFromPoint(args.x, args.y); + if (!element) return "default"; + if (element.closest("input,textarea,[contenteditable=true]")) return "text"; + return getComputedStyle(element).cursor;`, + point, + ), + ) + .catch(() => "default"); + return KNOWN_CURSORS.includes(cursor) ? cursor : "default"; +} + +export async function interactNatively( + page: NativeScripts, + request: InteractionRequest, +): Promise { + const { input, viewport } = request; + let point = pointOf(input); + switch (input.action) { + case "back": + case "forward": + case "reload": + await page.travel(input.action); + return {}; + case "click": + point = await click(page, input, viewport); + break; + case "hover": + if (!inside(point, viewport)) throw Error("Hover inside the current page."); + await deliver(page, { kind: "move", ...point }, "mousemove"); + break; + case "type": + await type(page, input); + break; + case "press": + if (!input.key) throw Error("A supported key is required."); + await deliver(page, { kind: "key", key: input.key }, "keyup"); + break; + case "choose": + await choose(page, input); + break; + case "scroll": { + const at = point ?? { x: viewport.width / 2, y: viewport.height / 2 }; + await deliver(page, { kind: "wheel", ...at, deltaY: input.deltaY ?? DEFAULT_SCROLL }, "wheel"); + break; + } + default: + throw Error(`The browser cannot ${input.action} here.`); + } + if (!point) return {}; + return { point, cursor: await cursorAt(page, point) }; +} diff --git a/runtime/browser/webkit-engine.ts b/runtime/browser/webkit-engine.ts new file mode 100644 index 0000000..1a19715 --- /dev/null +++ b/runtime/browser/webkit-engine.ts @@ -0,0 +1,261 @@ +import { createHash } from "node:crypto"; +import type { BrowserImage } from "../../src/browser"; +import type { NativeHost } from "../host"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + CaptureRequest, + InteractionFeedback, + InteractionRequest, + SurfacePlacement, +} from "./engine"; +import { inspectNativePage, interactNatively, type NativeScripts } from "./webkit-driver"; + +/** What `src-tauri/src/browser/macos` reports for each surface of a card. */ +interface NativePageState { + nativeId: string; + opener: string | null; + url: string; + title: string; + loading: boolean; + loads: number; +} + +/** WebKit tells MemCode nothing on its own, so the runtime asks this often. */ +const REFRESH_MS = 300; +const NAVIGATION_TIMEOUT_MS = 20000; +const NAVIGATION_POLL_MS = 80; +const HISTORY_QUIET_MS = 1500; + +/** A stable WebKit data store per card, unrelated to any other card's. */ +function cardProfile(taskId: string) { + return "worker-" + createHash("sha256").update(taskId).digest("hex"); +} + +class WebKitPage implements BrowserPage { + private current: Omit = { + url: "about:blank", + title: "", + loading: false, + loads: 0, + }; + private closed = false; + private navigated: Array<() => void> = []; + private loaded: Array<() => void> = []; + private closing: Array<() => void> = []; + constructor( + readonly nativeId: string, + private tabs: WebKitTabs, + ) {} + url() { + return this.current.url; + } + async title() { + return this.current.title; + } + isClosed() { + return this.closed; + } + async goto(url: string) { + const before = this.current.loads; + await this.tabs.call("browser_navigate", { nativeId: this.nativeId, url }); + await this.settle(before); + } + /** Back, forward and reload: the page moves on its own once WebKit has it. */ + async travel(action: "back" | "forward" | "reload") { + const before = this.current.loads; + await this.tabs.call("browser_history", { nativeId: this.nativeId, action }); + await this.settle(before, false); + } + inspect() { + return inspectNativePage(this.scripts()); + } + scripts(): NativeScripts { + return { + url: () => this.url(), + title: () => this.title(), + run: (script) => + this.tabs.call("browser_eval", { nativeId: this.nativeId, script }), + input: (input) => this.tabs.call("browser_input", { nativeId: this.nativeId, input }), + travel: (action) => this.travel(action), + }; + } + onNavigated(listener: () => void) { + this.navigated.push(listener); + } + onLoaded(listener: () => void) { + this.loaded.push(listener); + } + onClosed(listener: () => void) { + this.closing.push(listener); + } + update(next: NativePageState) { + const previous = this.current; + this.current = { url: next.url, title: next.title, loading: next.loading, loads: next.loads }; + if (next.loads !== previous.loads || next.url !== previous.url) + for (const listener of this.navigated) listener(); + if (next.title !== previous.title || (previous.loading && !next.loading)) + for (const listener of this.loaded) listener(); + } + markClosed() { + if (this.closed) return; + this.closed = true; + for (const listener of this.closing) listener(); + } + /** + * Waits until a new document has committed and stopped loading. A navigation + * that stops without committing failed (no network, refused address). Back or + * forward with no history does nothing, so those give up quietly. + */ + private async settle(before: number, expectNavigation = true) { + const started = Date.now(); + let loading = false; + for (;;) { + await this.tabs.sync(); + if (this.closed) throw Error("The browser tab closed."); + loading ||= this.current.loading; + const committed = this.current.loads > before, + elapsed = Date.now() - started; + if (committed && !this.current.loading) return; + if (loading && !committed && !this.current.loading) + throw Error("The page could not be opened."); + if (!expectNavigation && !loading && !committed && elapsed > HISTORY_QUIET_MS) return; + if (elapsed > NAVIGATION_TIMEOUT_MS) { + if (committed) return; + throw Error("The page took too long to open."); + } + await new Promise((resolve) => setTimeout(resolve, NAVIGATION_POLL_MS)); + } + } +} + +function webkitPage(page: BrowserPage): WebKitPage { + return page as WebKitPage; +} + +class WebKitTabs implements BrowserTabs { + private pages = new Map(); + private listener?: (page: BrowserPage, replaces?: BrowserPage) => void; + private timer?: NodeJS.Timeout; + private refreshing?: Promise; + private stopped = false; + constructor( + private host: NativeHost, + private taskId: string, + ) {} + call(method: string, input: Record = {}) { + return this.host.call(method, { taskId: this.taskId, ...input }); + } + async newPage() { + const { nativeId } = await this.call<{ nativeId: string }>("browser_create", { + profile: cardProfile(this.taskId), + }); + const page = new WebKitPage(nativeId, this); + this.pages.set(nativeId, page); + this.watch(); + return page; + } + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void) { + this.listener = listener; + } + /** One refresh at a time; callers that arrive meanwhile share it. */ + sync() { + this.refreshing ??= this.refresh().finally(() => { + this.refreshing = undefined; + }); + return this.refreshing; + } + async interact(page: BrowserPage, request: InteractionRequest): Promise { + return interactNatively(webkitPage(page).scripts(), request); + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const image = await this.call<{ data: string; width: number; height: number }>( + "browser_capture", + { nativeId: webkitPage(page).nativeId, scale: request.scale, format: request.format }, + ); + return { + mimeType: `image/${request.format}`, + data: image.data, + width: Math.round(image.width), + height: Math.round(image.height), + }; + } + async resize() {} + async closePage(page: BrowserPage) { + const native = webkitPage(page); + await this.call("browser_close", { nativeId: native.nativeId }); + this.pages.delete(native.nativeId); + native.markClosed(); + } + async close() { + this.stop(); + await this.call("browser_close_task"); + for (const page of this.pages.values()) page.markClosed(); + this.pages.clear(); + } + stop() { + this.stopped = true; + clearInterval(this.timer); + } + private watch() { + if (this.timer || this.stopped) return; + this.timer = setInterval(() => void this.sync().catch(() => {}), REFRESH_MS); + this.timer.unref?.(); + } + private async refresh() { + if (this.stopped) return; + const states = await this.call("browser_pages"); + const present = new Set(); + for (const state of states) { + present.add(state.nativeId); + this.adopt(state)?.update(state); + } + for (const [nativeId, page] of this.pages) + if (!present.has(nativeId)) { + this.pages.delete(nativeId); + page.markClosed(); + } + } + /** Known tabs, plus windows a page opened; a tab still being created waits. */ + private adopt(state: NativePageState) { + const known = this.pages.get(state.nativeId); + if (known || !state.opener) return known; + const popup = new WebKitPage(state.nativeId, this); + this.pages.set(state.nativeId, popup); + this.listener?.(popup); + return popup; + } +} + +/** macOS: each card's tab is a real WKWebView over the card. */ +export class WebKitEngine implements BrowserEngine { + readonly native = true; + private cards = new Set(); + constructor(private host: NativeHost) {} + connected() { + return true; + } + async open(_viewport: unknown, _density: number, taskId: string) { + const tabs = new WebKitTabs(this.host, taskId); + this.cards.add(tabs); + return tabs; + } + async surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement) { + if (!page) { + await this.host.call("browser_hide_all"); + return; + } + await this.host.call("browser_surface", { + taskId, + nativeId: webkitPage(page).nativeId, + ...placement, + }); + } + async close() { + const allocated = this.cards.size > 0; + for (const card of this.cards) card.stop(); + this.cards.clear(); + if (allocated) await this.host.call("browser_close_all"); + } +} diff --git a/runtime/catalog.ts b/runtime/catalog.ts index 4c418f9..03a873c 100644 --- a/runtime/catalog.ts +++ b/runtime/catalog.ts @@ -3,6 +3,7 @@ import { probeClaudeCatalog } from "./agents/claude"; import { codexCatalogGeneration } from "./agents/codex-models"; import { probeCursorCatalog } from "./agents/cursor"; import { probeStandardCatalog } from "./agents/standard-acp"; +import { inspectDshProfiles, defaultDshProfile } from "./dsh-profiles"; import { commandIdentity, findCommand, @@ -15,7 +16,15 @@ import { type ModelOption, } from "../src/shared"; -const cached = new Map }>(); +const cached = new Map< + Harness, + { expires: number; generation: number; profile?: string; value: Promise } +>(); + +export function invalidateHarnessCache(id?: Harness): void { + if (id) cached.delete(id); + else cached.clear(); +} let cursorCache: { identity: string; expires: number; models: Promise } | undefined; function cursorModels(command: NonNullable>>, refresh: boolean) { @@ -28,7 +37,13 @@ function cursorModels(command: NonNullable { +type DshInspection = Awaited>; + +async function discoverOne( + id: Harness, + refresh: boolean, + dshInfo?: DshInspection, +): Promise { const [command, desktopAppPath] = await Promise.all([findCommand(id), findDesktopApp(id)]); let models: ModelOption[] = []; let allModelsDenied = false; @@ -39,7 +54,19 @@ async function discoverOne(id: Harness, refresh: boolean): Promise []); + if (command && id === "copilot") + models = await probeStandardCatalog(id, command).catch(() => []); + if (command && id === "dsh") { + const canProbeDsh = + !dshInfo?.activeProfileIssue || + (dshInfo.activeProfileIssue === "missing" && + dshInfo.activeProfile === defaultDshProfile); + if (canProbeDsh) { + models = await probeStandardCatalog(id, command, dshInfo?.activeProfile).catch( + () => [], + ); + } + } return { id, name: harnessNames[id], @@ -47,6 +74,12 @@ async function discoverOne(id: Harness, refresh: boolean): Promise profile.name), + activeProfile: dshInfo.activeProfile, + } + : {}), models, ...(allModelsDenied ? { allModelsDenied } : {}), note: command @@ -58,14 +91,34 @@ async function discoverOne(id: Harness, refresh: boolean): Promise { +export async function discoverHarnesses( + refresh = false, + only?: Harness, + options?: { dshProfile?: string }, +): Promise { const ids: Harness[] = only ? [only] : ["codex", "claude", "cursor", "copilot", "dsh"]; - return Promise.all(ids.map((id) => { + return Promise.all(ids.map(async (id) => { + const dshInfo = + id === "dsh" + ? await inspectDshProfiles(options?.dshProfile).catch(() => undefined) + : undefined; + const profile = dshInfo?.activeProfile; const existing = cached.get(id); const generation = id === "codex" ? codexCatalogGeneration : 0; - if (existing && existing.generation === generation && (!refresh || existing.expires === Infinity) && Date.now() < existing.expires) + if ( + existing && + existing.generation === generation && + existing.profile === profile && + (!refresh || existing.expires === Infinity) && + Date.now() < existing.expires + ) return existing.value; - const entry = { expires: Infinity, generation, value: discoverOne(id, refresh) }; + const entry = { + expires: Infinity, + generation, + profile, + value: discoverOne(id, refresh, dshInfo), + }; cached.set(id, entry); void entry.value.then(() => { entry.expires = Date.now() + 60000; }, () => { cached.delete(id); }); return entry.value; diff --git a/runtime/commands.ts b/runtime/commands.ts index 112f0d5..930e1dd 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -1,6 +1,15 @@ -import { access, readdir, stat } from "node:fs/promises"; +import { access, readdir, readFile, stat } from "node:fs/promises"; import { constants } from "node:fs"; -import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + normalize, + resolve, + sep, +} from "node:path"; import { homedir } from "node:os"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -29,11 +38,81 @@ export function commandIdentity(command: Command): string { } export async function findDesktopApp( name: string, - options: MacCommandOptions & { platform?: NodeJS.Platform } = {}, + options: MacCommandOptions & { + platform?: NodeJS.Platform; + windowsCandidates?: readonly string[]; + } = {}, ): Promise { - return (options.platform ?? process.platform) === "darwin" - ? findMacDesktopApp(name, options) - : null; + const platform = options.platform ?? process.platform; + if (platform === "darwin") return findMacDesktopApp(name, options); + if (platform !== "win32" || name !== "dsh") return null; + + const env = options.environment ?? process.env; + const localAppData = env.LOCALAPPDATA ?? join(options.home ?? homedir(), "AppData", "Local"); + const programFiles = env.ProgramFiles ?? "C:\\Program Files"; + const candidates = options.windowsCandidates ?? [ + join(localAppData, "Programs", "DeepSeek Harness", "DeepSeek Harness.exe"), + join(programFiles, "DeepSeek Harness", "DeepSeek Harness.exe"), + ]; + for (const exePath of candidates) { + try { + if ((await stat(exePath)).isFile() && (await exists(join(dirname(exePath), "resources", "app.asar")))) { + return exePath; + } + } catch { + /* Candidate installation is absent. */ + } + } + return null; +} + +function expandWindowsEnvVars(raw: string, env: NodeJS.ProcessEnv): string { + const lookup = new Map(); + for (const [k, v] of Object.entries(env)) { + if (v !== undefined) lookup.set(k.toLowerCase(), v); + } + return raw.replace(/%([^%]+)%/g, (match, name: string) => lookup.get(name.toLowerCase()) ?? match); +} + +export async function refreshWindowsUserPath(): Promise { + if (process.platform !== "win32") return []; + try { + const regExe = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "reg.exe"); + const { stdout } = await promisify(execFile)( + regExe, + ["query", "HKCU\\Environment", "/v", "Path"], + { shell: false, windowsHide: true, timeout: 5000, encoding: "utf8" }, + ); + const match = /^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(stdout); + if (!match) return []; + + const discovered = expandWindowsEnvVars(match[1], process.env) + .split(delimiter) + .map((entry) => entry.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + + const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") ?? "PATH"; + const existing = (process.env[pathKey] ?? "") + .split(delimiter) + .map((entry) => entry.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + const seen = new Set(existing.map((entry) => entry.toLowerCase())); + const added: string[] = []; + for (const dir of discovered) { + const lower = dir.toLowerCase(); + if (!seen.has(lower)) { + seen.add(lower); + existing.push(dir); + added.push(dir); + } + } + if (added.length > 0) { + process.env[pathKey] = existing.join(delimiter); + } + return added; + } catch { + return []; + } } export async function exists(path: string): Promise { try { @@ -95,6 +174,89 @@ async function direct( return null; } +const WINDOWS_DSH_SHIM = + /^\s*"%~dp0\\?([^"%\r\n]+\.exe)"\s+--expose-internals\s+"%~dp0\\?([^"%\r\n]+\.(?:c|m)?js)"\s+%\*\s*$/i; + +async function dshInstallCommand( + executable: string, + script: string, +): Promise { + // Bind the entry to the installation that owns the executable, so a changed + // .exe cannot keep a saved worker approval for the same script identity. + if (basename(executable).toLowerCase() !== "deepseek harness.exe") + return null; + const appAsar = join(dirname(executable), "resources", "app.asar"); + if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) + return null; + // A leftover shim from an uninstall must not look "installed", and must not + // block the node_modules fallback in the same directory. + if (!(await exists(executable)) || !(await exists(appAsar))) return null; + return { + command: executable, + prefix: ["--expose-internals", script], + identity: script, + env: { ELECTRON_RUN_AS_NODE: "1" }, + }; +} + +/** + * A saved dsh identity points inside the installer's app.asar, which ordinary + * filesystem access cannot read. Rebuild the command from the owning + * installation before the configured-path existence check rejects it. + */ +async function savedArchiveCommand( + name: string, + configured: string, +): Promise { + if (name !== "dsh" || process.platform !== "win32" || !isAbsolute(configured)) + return null; + const normalized = normalize(configured); + // A saved identity must be the exact entry the shim resolved. Reject `..` + // segments that would redirect an approved identity to another installation. + if (normalized.toLowerCase() !== configured.toLowerCase()) return null; + const parts = normalized.split(sep); + const archive = parts.findLastIndex( + (part) => part.toLowerCase() === "app.asar", + ); + if ( + archive < 2 || + parts[archive - 1]?.toLowerCase() !== "resources" || + archive === parts.length - 1 || + !/\.(?:c|m)?js$/i.test(parts[parts.length - 1]) + ) + return null; + const install = parts.slice(0, archive - 1).join(sep); + return dshInstallCommand(join(install, "DeepSeek Harness.exe"), normalized); +} + +/** + * The launcher installed by the official DeepSeek Harness CLI is a .cmd shim + * that delegates to an Electron executable. Worker sessions spawn with + * `shell: false`, which cannot run a batch file on Windows. Normalize the shim + * into the executable, argument prefix and environment the installer declares, + * so every existing argument-array spawn site works unchanged. + */ +async function windowsShimCommand(path: string): Promise { + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + return null; + } + // Only a line that fully matches the official launcher shape counts. A + // comment or echo that merely mentions the flag cannot shadow the real line. + let match: RegExpMatchArray | null = null; + for (const line of text.split(/\r?\n/)) { + match = line.match(WINDOWS_DSH_SHIM); + if (match) break; + } + if (!match) return null; + const base = dirname(path); + const command = resolve(base, match[1]); + const script = resolve(base, match[2]); + return dshInstallCommand(command, script); +} + async function cursorRuntime(): Promise { const root = join(homedir(), "AppData", "Local", "cursor-agent", "versions"); try { @@ -197,6 +359,8 @@ export async function findCommand( options: MacCommandOptions & { platform?: NodeJS.Platform } = {}, ): Promise { if (configured) { + const archived = await savedArchiveCommand(name, configured); + if (archived) return archived; if (!isAbsolute(configured) || !(await exists(configured))) return null; if (/\.(cjs|mjs|js)$/i.test(configured)) return { @@ -227,19 +391,31 @@ export async function findCommand( .filter(Boolean), ), ]; + const extensions = + process.platform === "win32" + ? name === "dsh" + ? [".exe", ".cmd"] + : [".exe"] + : [""]; for (const dir of dirs) { const names = name === "cursor" ? ["cursor-agent", "agent"] : [name]; for (const candidate of names) { - const path = join( - dir, - candidate + (process.platform === "win32" ? ".exe" : ""), - ); - if ((await exists(path)) && (await stat(path)).isFile()) + for (const extension of extensions) { + const path = join(dir, candidate + extension); + if (!((await exists(path)) && (await stat(path)).isFile())) continue; + // A batch shim cannot be passed to spawn with `shell: false`. + if (extension === ".cmd") { + const normalized = + name === "dsh" ? await windowsShimCommand(path) : null; + if (normalized) return normalized; + continue; + } return { command: path, prefix: [], ...(name === "cursor" ? { env: { CURSOR_INVOKED_AS: "agent" } } : {}), }; + } } const packageEntry = name === "memtrace" diff --git a/runtime/deletion.ts b/runtime/deletion.ts index adb5609..6731ebc 100644 --- a/runtime/deletion.ts +++ b/runtime/deletion.ts @@ -42,8 +42,16 @@ function deleteStories( for (const child of children) ids.add(child.id); } requireStopped(state.tasks.filter((task) => ids.has(task.id))); - // All validation precedes mutation. Source files, branches, output files and Git - // history are deliberately outside this metadata-only operation. + // All validation precedes mutation. + removeStories(state, ids); + return { deletedIds: [...ids], reassignedStoryIds: [] }; +} + +/** + * Removes tasks and every record that names them. Source files, branches, output + * files and Git history are deliberately outside this metadata-only operation. + */ +function removeStories(state: AppState, ids: Set): void { const artifactIds = new Set( state.artifacts .filter((artifact) => ids.has(artifact.taskId)) @@ -139,7 +147,6 @@ function deleteStories( for (const id of ids) delete state.planning.observations[id]; if (state.onboarding?.storyId && ids.has(state.onboarding.storyId)) delete state.onboarding.storyId; - return { deletedIds: [...ids], reassignedStoryIds: [] }; } function deleteEpic(state: AppState, id: string): DeletionResult { @@ -205,11 +212,87 @@ function deleteCycle(state: AppState, id: string): DeletionResult { }; } +/** + * Removes a project from MemCode on this computer: its board and everything kept + * for it. Its folder, its code and the files workers made stay on disk. A shared + * project is disconnected from this computer first; it stays shared for the others. + */ +async function deleteProject( + state: AppState, + id: string, + forgetSharing?: (projectId: string) => Promise, +): Promise { + const project = state.projects.find((item) => item.id === id); + if (!project) throw Error("Project not found."); + if (state.projects.length === 1) + throw Error("Add another project before deleting the last one."); + if (state.team?.some((room) => room.projectId === id)) + throw Error( + `${project.name} is in a Team Sync team. Leave the team on its Team page first.`, + ); + const tasks = state.tasks.filter((task) => task.projectId === id); + if (tasks.some(isActive)) + throw Error(`Stop the workers running in ${project.name} before deleting it.`); + if (state.sharedProjectLinks?.some((link) => link.projectId === id)) + await forgetSharing?.(id); + removeStories(state, new Set(tasks.map((task) => task.id))); + removeProjectRecords(state, id); + return { deletedIds: [id], reassignedStoryIds: [] }; +} + +/** Everything the workspace keeps for a project other than its tasks. */ +function removeProjectRecords(state: AppState, id: string): void { + const ofOtherProjects = (items: T[]) => + items.filter((item) => item.projectId !== id); + const goalIds = new Set( + state.epics.filter((epic) => epic.projectId === id).map((epic) => epic.id), + ); + state.projects = state.projects.filter((item) => item.id !== id); + state.epics = ofOtherProjects(state.epics); + state.cycles = ofOtherProjects(state.cycles); + state.workflowStates = ofOtherProjects(state.workflowStates); + state.customFields = ofOtherProjects(state.customFields); + state.savedViews = ofOtherProjects(state.savedViews); + state.qualitySnapshots = ofOtherProjects(state.qualitySnapshots); + state.fleetConflicts = ofOtherProjects(state.fleetConflicts); + state.artifacts = ofOtherProjects(state.artifacts); + state.planning.events = ofOtherProjects(state.planning.events); + if (state.fleetDeclarations) + state.fleetDeclarations = ofOtherProjects(state.fleetDeclarations); + if (state.fleetProposals) + state.fleetProposals = ofOtherProjects(state.fleetProposals); + if (state.sharedBoards) state.sharedBoards = ofOtherProjects(state.sharedBoards); + if (state.pullRequests) + state.pullRequests = state.pullRequests.filter( + (request) => !goalIds.has(request.epicId), + ); + if (state.planning.authoritativeProjects) + state.planning.authoritativeProjects = + state.planning.authoritativeProjects.filter((item) => item !== id); + delete state.reviewWorkflows?.[id]; + delete state.projectOnboarding?.[id]; + if (state.onboarding?.epicId && goalIds.has(state.onboarding.epicId)) + delete state.onboarding.epicId; + if (state.activeProjectId === id) + state.activeProjectId = ( + state.projects.find((item) => !item.example) ?? state.projects[0] + ).id; +} + export function registerDeletion( register: Register, state: () => AppState, changed: () => Promise, + options: { + /** Disconnects a shared project from this computer; the others keep it. */ + forgetSharing?(projectId: string): Promise; + } = {}, ): void { + register("project:delete", deleteEntitySchema, async ({ id }) => { + const result = await deleteProject(state(), id, options.forgetSharing); + await changed(); + return result; + }); register("story:delete", deleteStorySchema, async ({ id, cascade }) => { const result = deleteStories(state(), id, cascade); await changed(); diff --git a/runtime/dsh-desktop.ts b/runtime/dsh-desktop.ts new file mode 100644 index 0000000..8bbb7b3 --- /dev/null +++ b/runtime/dsh-desktop.ts @@ -0,0 +1,294 @@ +import { execFile } from "node:child_process"; +import { stat } from "node:fs/promises"; +import { delimiter, dirname, join } from "node:path"; +import { promisify } from "node:util"; +import type { DshDesktopCliInfo } from "../src/shared"; +import { childEnv, exists, refreshWindowsUserPath } from "./commands"; + +const execFileAsync = promisify(execFile); +const FINGERPRINT_RE = /^[a-f0-9]{64}$/i; +const SCRUB_ENV_RE = /KEY|SECRET|TOKEN|PASSWORD|^NODE_OPTIONS$|^NODE_PATH$/i; + +interface DesktopCliPaths { + isMac: boolean; + bundledNode: string; + commandManagerPath: string; + launcherPath: string; +} + +interface CommandManagerResponse { + ok: boolean; + code?: string; + message?: string; + state?: { + fingerprint?: unknown; + managed?: unknown; + available?: unknown; + activeCommand?: unknown; + launcher?: unknown; + directory?: unknown; + }; +} + +function resolveResourcesDir(desktopAppPath: string): { resourcesDir: string; isMac: boolean } { + const isMac = /\.app(?:[\\/]?)$/i.test(desktopAppPath) || process.platform === "darwin"; + const clean = desktopAppPath.replace(/[\\/]+$/, ""); + return { + isMac, + resourcesDir: isMac ? join(clean, "Contents", "Resources") : join(dirname(clean), "resources"), + }; +} + +function scrubbedCliEnv(): NodeJS.ProcessEnv { + const env = childEnv(); + for (const key of Object.keys(env)) { + if (SCRUB_ENV_RE.test(key)) delete env[key]; + } + return env; +} + +async function isFile(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +async function resolveDesktopCliPaths(desktopAppPath: string): Promise { + const { resourcesDir, isMac } = resolveResourcesDir(desktopAppPath); + const nodeNames = process.platform === "win32" ? ["node.exe", "node"] : ["node"]; + let bundledNode: string | null = null; + for (const sub of ["runtime", ""]) { + for (const nodeName of nodeNames) { + const candidate = sub + ? join(resourcesDir, sub, "primary-runtime", "dependencies", "node", "bin", nodeName) + : join(resourcesDir, "primary-runtime", "dependencies", "node", "bin", nodeName); + if (await isFile(candidate)) { + bundledNode = candidate; + break; + } + } + if (bundledNode) break; + } + if (!bundledNode) { + return "DeepSeek Harness Desktop bundled Node runtime was not found."; + } + + const commandManagerPath = join(resourcesDir, "runtime", "cli", "command-manager.js"); + if (!(await isFile(commandManagerPath))) { + return "DeepSeek Harness Desktop CLI manager was not found."; + } + + const launcherCandidates = isMac && process.platform !== "win32" + ? [join(resourcesDir, "runtime", "cli", "bin", "dsh")] + : [ + join(resourcesDir, "runtime", "cli", "bin", "dsh.cmd"), + join(resourcesDir, "runtime", "cli", "bin", "dsh"), + ]; + let launcherPath: string | null = null; + for (const candidate of launcherCandidates) { + if (await exists(candidate)) { + launcherPath = candidate; + break; + } + } + if (!launcherPath) { + return "DeepSeek Harness Desktop CLI launcher was not found."; + } + + return { isMac, bundledNode, commandManagerPath, launcherPath }; +} + +async function runCommandManager( + paths: DesktopCliPaths, + args: string[], +): Promise<{ parsed: CommandManagerResponse | null; errorMessage?: string }> { + let stdout = ""; + let stderr = ""; + let thrownMessage: string | undefined; + try { + const result = await execFileAsync(paths.bundledNode, [paths.commandManagerPath, ...args], { + shell: false, + windowsHide: true, + timeout: 15_000, + encoding: "utf8", + env: scrubbedCliEnv(), + }); + stdout = result.stdout ?? ""; + stderr = result.stderr ?? ""; + } catch (error) { + const err = error as { stdout?: string; stderr?: string; message?: string }; + stdout = typeof err.stdout === "string" ? err.stdout : ""; + stderr = typeof err.stderr === "string" ? err.stderr : ""; + thrownMessage = err.message; + } + + const lines = stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + for (let i = lines.length - 1; i >= 0; i--) { + try { + const candidate = JSON.parse(lines[i]) as CommandManagerResponse; + if (candidate && typeof candidate === "object" && typeof candidate.ok === "boolean") { + return { parsed: candidate }; + } + } catch { + /* Ignore non-JSON line and try earlier line. */ + } + } + return { + parsed: null, + errorMessage: stderr.trim() || thrownMessage || "Invalid response from Desktop CLI manager.", + }; +} + +async function inspectInternal( + desktopAppPath: string, +): Promise<{ info: DshDesktopCliInfo; fingerprint?: string; paths?: DesktopCliPaths }> { + const resolved = await resolveDesktopCliPaths(desktopAppPath); + if (typeof resolved === "string") { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: resolved, + }, + }; + } + + const { parsed, errorMessage } = await runCommandManager(resolved, ["inspect"]); + if (!parsed) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: errorMessage ?? "Failed to inspect DeepSeek Harness Desktop CLI.", + }, + }; + } + if (!parsed.ok) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: parsed.message || "Desktop CLI inspection returned an error.", + }, + }; + } + + const state = parsed.state; + if ( + !state || + typeof state.fingerprint !== "string" || + !FINGERPRINT_RE.test(state.fingerprint) || + typeof state.managed !== "boolean" || + typeof state.available !== "boolean" + ) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: "Desktop CLI inspection returned an unexpected response format.", + }, + }; + } + + const launcherPath = + typeof state.launcher === "string" && state.launcher.trim() + ? state.launcher + : resolved.launcherPath; + + return { + fingerprint: state.fingerprint, + paths: resolved, + info: { + desktopAppPath, + canInstall: true, + managed: state.managed, + available: state.available, + launcherPath, + ...(typeof state.activeCommand === "string" && state.activeCommand + ? { activeCommand: state.activeCommand } + : {}), + }, + }; +} + +export async function inspectDshDesktopCli(desktopAppPath: string): Promise { + return (await inspectInternal(desktopAppPath)).info; +} + +function prependWindowsPathDir(dir: string): void { + const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") ?? "PATH"; + const entries = (process.env[pathKey] ?? "") + .split(delimiter) + .map((part) => part.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + const lower = dir.toLowerCase(); + if (!entries.some((entry) => entry.toLowerCase() === lower)) { + process.env[pathKey] = [dir, ...entries].join(delimiter); + } +} + +export async function installDshDesktopCli( + desktopAppPath: string, +): Promise<{ installed: boolean; needsDesktopMenu?: boolean; message: string; launcherPath?: string }> { + const inspected = await inspectInternal(desktopAppPath); + if (!inspected.info.canInstall || !inspected.fingerprint || !inspected.paths) { + return { + installed: false, + message: inspected.info.reason ?? "DeepSeek Harness Desktop CLI helper is unavailable.", + }; + } + + const { parsed, errorMessage } = await runCommandManager(inspected.paths, [ + "install", + inspected.fingerprint, + ]); + if (!parsed) { + return { + installed: false, + message: errorMessage ?? "Failed to install DeepSeek Harness CLI.", + }; + } + + if (!parsed.ok) { + if (inspected.paths.isMac && (parsed.code === "EACCES" || parsed.code === "EPERM")) { + return { + installed: false, + needsDesktopMenu: true, + message: "Open DeepSeek Harness Desktop and choose Manage dsh Command… to authorize /usr/local/bin/dsh.", + }; + } + return { + installed: false, + message: parsed.message || "Failed to install DeepSeek Harness CLI.", + }; + } + + const launcherPath = + typeof parsed.state?.launcher === "string" && parsed.state.launcher.trim() + ? parsed.state.launcher + : inspected.info.launcherPath ?? inspected.paths.launcherPath; + + if (process.platform === "win32") { + await refreshWindowsUserPath(); + prependWindowsPathDir(dirname(launcherPath)); + } + + return { + installed: true, + message: "DeepSeek Harness CLI installed.", + launcherPath, + }; +} diff --git a/runtime/dsh-migration.ts b/runtime/dsh-migration.ts new file mode 100644 index 0000000..fb2a095 --- /dev/null +++ b/runtime/dsh-migration.ts @@ -0,0 +1,1161 @@ +import { execFile } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { isAbsolute, join, relative, resolve } from "node:path"; +import { promisify } from "node:util"; +import type { + DshDesktopDiff, + DshDesktopProviderCandidate, + DshDryRunResult, + DshProviderFailure, + DshSkippedDesktopItem, + ModelOption, +} from "../src/shared"; +import { probeStandardCatalog } from "./agents/standard-acp"; +import { childEnv, type Command } from "./commands"; +import { + inspectDshProfiles, + isTemporaryDryRunProfile, + normalizeDshProfile, + resolveDshHome, +} from "./dsh-profiles"; +import { + hasExplicitJsTag, + hasInlineSecret, + hasJsTag, + parseDshPatchYaml, + stringifyDshPatchYaml, +} from "./dsh-yaml"; + +const execFileAsync = promisify(execFile); +const STALE_DRYRUN_AGE_MS = 60 * 60 * 1000; +const DRYRUN_MARKER = ".memcode-dryrun"; +const DRYRUN_MARKER_TEXT = "memcode-dryrun\n"; +/** Every file `dsh plugin add` or a patch import can change, restored on rollback. */ +const PROFILE_FILES = [ + "package.json", + "cordis.patch.yml", + "pnpm-workspace.yaml", + "pnpm-lock.yaml", +] as const; +type ProfileFile = (typeof PROFILE_FILES)[number]; +type ProfileSnapshot = Map; + +export type StrictAcpProbe = (profile: string, command: Command) => Promise; + +/** + * What a successful dry-run verified. Apply accepts only this plan and refuses + * to mutate the profile when Desktop, the home patch, or the target changed. + */ +export interface DshMigrationPlan { + fingerprint: string; + targetProfile: string; + selectedIds: string[]; + /** Catalog entries the dry-run saw appear; apply must show every one. */ + expectedModelIds: string[]; +} + +interface DesktopPatchData { + piAiProviders: Map>; + pluginConfigRows: Map>; + homePatch: Buffer | null; + diff: DshDesktopDiff; +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +function buildDshEnv(dshHome: string, command: Command, env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return { + ...childEnv(), + ...command.env, + ...(env !== process.env ? env : {}), + DSH_HOME: dshHome, + }; +} + +function withDshHomeCommand(command: Command, dshHome: string, env: NodeJS.ProcessEnv): Command { + return { + ...command, + env: { + ...command.env, + ...(env !== process.env && env.PATH ? { PATH: env.PATH } : {}), + DSH_HOME: dshHome, + }, + }; +} + +function extractErrorMessage(error: unknown): string { + if (error instanceof Error) { + const err = error as Error & { stderr?: string; stdout?: string }; + const detail = err.stderr?.trim() || err.stdout?.trim(); + return detail ? `${err.message}: ${detail}` : err.message; + } + return String(error); +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} + +async function readOptional(path: string): Promise { + try { + return await readFile(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +async function readJsonSafe(path: string): Promise> { + try { + const parsed = JSON.parse(await readFile(path, "utf8")); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +async function readPatchStrict(path: string): Promise<{ entries: any[]; hasJsExpression: boolean }> { + const text = await readOptional(path); + return text === null ? { entries: [], hasJsExpression: false } : parseDshPatchYaml(text.toString("utf8")); +} + +async function readPatchSafe(path: string): Promise<{ entries: any[]; hasJsExpression: boolean }> { + try { + return await readPatchStrict(path); + } catch { + return { entries: [], hasJsExpression: false }; + } +} + +/** Snapshot every profile file; an unreadable existing file aborts instead of reading as absent. */ +async function readProfileSnapshot(profileDir: string): Promise { + const snapshot: ProfileSnapshot = new Map(); + for (const file of PROFILE_FILES) { + try { + snapshot.set(file, await readOptional(join(profileDir, file))); + } catch (error) { + throw new Error(`Cannot read existing profile file "${file}": ${extractErrorMessage(error)}`); + } + } + return snapshot; +} + +function isPiAiRow(entry: unknown): entry is Record { + return ( + isPlainObject(entry) && + (entry.id === "llm-pi-ai" || entry.name === "@deepseek-ai/dsh-llm-pi-ai") + ); +} + +/** + * The llm-pi-ai providers one patch layer sets. A row that sets `config` + * replaces the whole configuration of earlier layers and rows, so only the + * last such row counts. Providers under an explicitly `!!js`-tagged entry, + * config or providers container are never offered, but an untagged sibling of + * a tagged provider still is. + */ +function extractPiAiProviders(entries: unknown[]): { + providers: Map>; + tainted: boolean; + configured: boolean; +} { + let providers = new Map>(); + let tainted = false; + let configured = false; + for (const entry of entries) { + if (!isPiAiRow(entry)) continue; + if (hasExplicitJsTag(entry)) { + configured = true; + providers = new Map(); + tainted = true; + continue; + } + if (!Object.prototype.hasOwnProperty.call(entry, "config")) continue; + configured = true; + providers = new Map(); + tainted = false; + const config = entry.config; + if (!isPlainObject(config) || hasExplicitJsTag(config)) { + tainted = hasJsTag(entry); + continue; + } + const rawProviders = config.providers; + if (!isPlainObject(rawProviders) || hasExplicitJsTag(rawProviders)) { + tainted = hasJsTag(config); + continue; + } + for (const [providerId, providerConfig] of Object.entries(rawProviders)) { + if (isPlainObject(providerConfig)) providers.set(providerId, providerConfig); + } + } + return { providers, tainted, configured }; +} + +function extractModelIds(providerConfig: Record): string[] { + if (!Array.isArray(providerConfig.models)) return []; + const ids: string[] = []; + for (const model of providerConfig.models) { + if (typeof model === "string" && model.trim()) ids.push(model.trim()); + else if (isPlainObject(model)) { + const id = typeof model.id === "string" ? model.id.trim() : typeof model.name === "string" ? model.name.trim() : ""; + if (id) ids.push(id); + } + } + return ids; +} + +function findMatchingPluginRow( + entries: unknown[], + pkgName: string, +): Record | undefined { + const shortName = pkgName.replace(/^@[^/]+\//, "").replace(/^dsh-/, ""); + for (const entry of entries) { + if (!isPlainObject(entry)) continue; + if (Array.isArray(entry.insert) && !entry.id && !entry.name) continue; + if (entry.name === pkgName || entry.id === shortName || entry.id === pkgName) { + return entry; + } + } + return undefined; +} + +function buildPluginSpec(pkgName: string, rawSpec: unknown, desktopDir: string): { + spec: string; + source: "registry" | "local-link"; + defaultSelected: boolean; + warning?: string; +} { + const trimmed = typeof rawSpec === "string" ? rawSpec.trim() : ""; + const local = /^(link|file):([\s\S]*)$/.exec(trimmed); + if (local) { + // dsh runs plugin commands inside the selected profile directory, so a + // relative path must be resolved against Desktop's profile, not copied. + const path = local[2]; + const absolute = isAbsolute(path) || /^[A-Za-z]:[\\/]/.test(path) || /^\\\\/.test(path); + return { + spec: `${local[1]}:${absolute ? path : resolve(desktopDir, path)}`, + source: "local-link", + defaultSelected: false, + warning: "Local linked plugin may add non-LLM hooks or require Desktop services.", + }; + } + const spec = trimmed + ? /^(?:https?:|git\+|npm:|github:|workspace:)/i.test(trimmed) + ? trimmed + : `${pkgName}@${trimmed}` + : pkgName; + return { + spec, + source: "registry", + defaultSelected: true, + }; +} + +async function computeDesktopDiff( + targetProfile: string, + env: NodeJS.ProcessEnv, +): Promise { + const normalizedTarget = normalizeDshProfile(targetProfile); + const dshHome = resolveDshHome(env); + const desktopDir = join(dshHome, "profiles", "desktop"); + const targetDir = join(dshHome, "profiles", normalizedTarget); + const homePatchPath = join(dshHome, "cordis.patch.yml"); + let homePatchBytes: Buffer | null = null; + let homePatchUnreadable = false; + try { + homePatchBytes = await readOptional(homePatchPath); + } catch { + homePatchUnreadable = true; + } + + if (!(await isDirectory(desktopDir))) { + return { + piAiProviders: new Map(), + pluginConfigRows: new Map(), + homePatch: homePatchBytes, + diff: { + targetProfile: normalizedTarget, + desktopPresent: false, + providers: [], + skipped: [], + }, + }; + } + + let desktopPatch: { entries: any[]; hasJsExpression: boolean } = { entries: [], hasJsExpression: false }; + let desktopPatchUnsupported = false; + try { + desktopPatch = await readPatchStrict(join(desktopDir, "cordis.patch.yml")); + } catch { + desktopPatchUnsupported = true; + } + let homePatch: { entries: any[]; hasJsExpression: boolean } = { entries: [], hasJsExpression: false }; + let homePatchUnsupported = homePatchUnreadable; + try { + homePatch = homePatchBytes === null ? homePatch : parseDshPatchYaml(homePatchBytes.toString("utf8")); + } catch { + homePatchUnsupported = true; + } + const [desktopPkg, targetPatch, targetPkg] = await Promise.all([ + readJsonSafe(join(desktopDir, "package.json")), + readPatchSafe(join(targetDir, "cordis.patch.yml")), + readJsonSafe(join(targetDir, "package.json")), + ]); + + const providers: DshDesktopProviderCandidate[] = []; + const skipped: DshSkippedDesktopItem[] = []; + if (desktopPatchUnsupported) { + skipped.push({ + name: "cordis.patch.yml", + reason: "Desktop cordis.patch.yml uses unsupported YAML syntax and was skipped.", + }); + } + const piAiProviders = new Map>(); + const pluginConfigRows = new Map>(); + + const desktopPiAi = extractPiAiProviders(desktopPatch.entries); + // dsh composes the profile patch first and the home patch last; a home row + // that sets llm-pi-ai's config replaces the profile's provider list. + const homePiAi = extractPiAiProviders(homePatch.entries); + const effective = homePiAi.configured ? homePiAi : extractPiAiProviders(targetPatch.entries); + const existingModels = new Map>(); + for (const [providerId, cfg] of effective.providers) { + existingModels.set(providerId, new Set(extractModelIds(cfg))); + } + const maskedReason = homePatchUnsupported + ? `${homePatchPath} could not be read or uses unsupported YAML, so MemCode cannot tell whether it replaces this profile's providers.` + : homePiAi.configured + ? `${homePatchPath} sets llm-pi-ai for every profile and would hide this import. Add the provider there instead.` + : undefined; + + if (desktopPiAi.tainted) { + skipped.push({ + name: "llm-pi-ai", + reason: "Desktop llm-pi-ai configuration contains !!js expression and was skipped.", + }); + } else { + for (const [providerId, cfg] of desktopPiAi.providers) { + if (hasJsTag(cfg)) { + skipped.push({ + name: providerId, + reason: "Contains !!js expression; skipped for safety.", + }); + continue; + } + if (hasInlineSecret(cfg)) { + skipped.push({ + name: providerId, + reason: "Contains inline credential or secret; use apiKeyEnv or .credentials.yaml.", + }); + continue; + } + const models = extractModelIds(cfg); + const existing = existingModels.get(providerId); + const missingModels = existing ? models.filter((m) => !existing.has(m)) : undefined; + if (existing && (!missingModels || missingModels.length === 0)) continue; + if (maskedReason) { + skipped.push({ name: providerId, reason: maskedReason }); + continue; + } + + piAiProviders.set(providerId, cfg); + const displayName = + typeof cfg.displayName === "string" && cfg.displayName.trim() + ? cfg.displayName.trim() + : providerId; + providers.push({ + id: `pi-ai:${providerId}`, + kind: "pi-ai", + name: displayName, + providerId, + models, + ...(missingModels ? { missingModels } : {}), + defaultSelected: true, + }); + } + } + + const targetPackages = new Set([ + ...(Array.isArray((targetPkg.dsh as { profile?: { bundles?: unknown[] } } | undefined)?.profile?.bundles) + ? ((targetPkg.dsh as { profile: { bundles: unknown[] } }).profile.bundles.filter( + (b): b is string => typeof b === "string", + )) + : []), + ...(isPlainObject(targetPkg.dependencies) ? Object.keys(targetPkg.dependencies) : []), + ]); + + const desktopBundles = Array.isArray( + (desktopPkg.dsh as { profile?: { bundles?: unknown[] } } | undefined)?.profile?.bundles, + ) + ? ((desktopPkg.dsh as { profile: { bundles: unknown[] } }).profile.bundles.filter( + (b): b is string => typeof b === "string", + )) + : []; + const desktopDeps = isPlainObject(desktopPkg.dependencies) ? desktopPkg.dependencies : {}; + const desktopPackages = [...new Set([...desktopBundles, ...Object.keys(desktopDeps)])]; + + for (const pkgName of desktopPackages) { + if (pkgName.startsWith("@deepseek-ai/") || targetPackages.has(pkgName)) continue; + + const pkgDir = join(desktopDir, "node_modules", ...pkgName.split("/")); + const pkgJson = await readJsonSafe(join(pkgDir, "package.json")); + const peers = isPlainObject(pkgJson.peerDependencies) ? pkgJson.peerDependencies : null; + if (!peers || !Object.prototype.hasOwnProperty.call(peers, "@deepseek-ai/dsh-llm")) { + continue; + } + + const exportsField = isPlainObject(pkgJson.exports) ? pkgJson.exports : null; + const dotExport = exportsField && isPlainObject(exportsField["."]) ? exportsField["."] : null; + const mainRel = + typeof pkgJson.main === "string" && pkgJson.main.trim() + ? pkgJson.main.trim() + : typeof dotExport?.default === "string" + ? dotExport.default + : typeof exportsField?.["."] === "string" + ? (exportsField["."] as string) + : ""; + if (!mainRel) continue; + + const mainPath = join(pkgDir, mainRel); + if (relative(pkgDir, mainPath).startsWith("..")) continue; + let mainSource = ""; + try { + mainSource = await readFile(mainPath, "utf8"); + } catch { + continue; + } + if (!mainSource.includes("registerAdapter(")) continue; + + const { spec, source, defaultSelected, warning } = buildPluginSpec( + pkgName, + desktopDeps[pkgName], + desktopDir, + ); + const configRow = findMatchingPluginRow(desktopPatch.entries, pkgName); + let hasConfigPatch = false; + if (configRow) { + if (hasJsTag(configRow) || hasInlineSecret(configRow)) { + skipped.push({ + name: pkgName, + reason: "Desktop config row contains !!js or inline secrets and was skipped.", + }); + } else { + pluginConfigRows.set(pkgName, configRow); + hasConfigPatch = true; + } + } + + providers.push({ + id: `plugin:${pkgName}`, + kind: "plugin", + name: pkgName, + providerId: pkgName, + models: [], + source, + spec, + ...(hasConfigPatch ? { hasConfigPatch: true } : {}), + defaultSelected, + ...(warning ? { warning } : {}), + }); + } + + return { + piAiProviders, + pluginConfigRows, + homePatch: homePatchBytes, + diff: { + targetProfile: normalizedTarget, + desktopPresent: true, + providers, + skipped, + }, + }; +} + +export async function diffDshDesktopModels( + targetProfile: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + return (await computeDesktopDiff(targetProfile, env)).diff; +} + +/** Every selected id must still be offered; stale or unknown ids are refused, never skipped. */ +function staleSelections(selectedIds: string[], data: DesktopPatchData): DshProviderFailure[] { + const offered = new Set(data.diff.providers.map((p) => p.id)); + return selectedIds + .filter((id) => !offered.has(id)) + .map((id) => ({ + id, + name: id.replace(/^(?:pi-ai|plugin):/, ""), + reason: "No longer offered by DeepSeek Harness Desktop. Reload the provider list and test again.", + })); +} + +function hashBytes(bytes: Buffer | null): string | null { + return bytes === null ? null : createHash("sha256").update(bytes).digest("hex"); +} + +/** Binds a plan to the exact Desktop sources, home patch and target files it tested. */ +function migrationFingerprint( + targetProfile: string, + selectedIds: string[], + data: DesktopPatchData, + snapshot: ProfileSnapshot, +): string { + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + const sources = [...selectedIds].sort().map((id) => { + const candidate = byId.get(id); + const providerId = candidate?.providerId ?? id; + return { + id, + spec: candidate?.spec ?? null, + models: candidate?.missingModels ?? candidate?.models ?? null, + config: data.piAiProviders.get(providerId) ?? data.pluginConfigRows.get(providerId) ?? null, + }; + }); + return createHash("sha256") + .update( + JSON.stringify({ + targetProfile, + sources, + home: hashBytes(data.homePatch), + files: PROFILE_FILES.map((file) => [file, hashBytes(snapshot.get(file) ?? null)]), + }), + ) + .digest("hex"); +} + +function mergePatchEntries( + existingEntries: any[], + selectedIds: string[], + data: DesktopPatchData, +): any[] { + const entries = cloneJson(existingEntries); + const selectedPiAi = selectedIds + .filter((id) => id.startsWith("pi-ai:")) + .map((id) => id.slice("pi-ai:".length)); + + if (selectedPiAi.length > 0) { + let piAiEntry = [...entries].reverse().find( + (entry) => isPiAiRow(entry) && Object.prototype.hasOwnProperty.call(entry, "config"), + ) ?? entries.find((entry) => isPiAiRow(entry)); + if (!piAiEntry) { + piAiEntry = { + id: "llm-pi-ai", + name: "@deepseek-ai/dsh-llm-pi-ai", + config: { providers: {} }, + }; + entries.push(piAiEntry); + } + if (!isPlainObject(piAiEntry.config)) piAiEntry.config = {}; + if (!isPlainObject(piAiEntry.config.providers)) piAiEntry.config.providers = {}; + + for (const providerId of selectedPiAi) { + const desktopCfg = data.piAiProviders.get(providerId); + if (!desktopCfg) continue; + const existingCfg = piAiEntry.config.providers[providerId]; + if (!isPlainObject(existingCfg)) { + piAiEntry.config.providers[providerId] = cloneJson(desktopCfg); + } else if (Array.isArray(desktopCfg.models)) { + const currentModels = Array.isArray(existingCfg.models) ? existingCfg.models : []; + const existingIds = new Set(extractModelIds(existingCfg)); + for (const model of desktopCfg.models) { + const modelId = + typeof model === "string" + ? model + : isPlainObject(model) + ? (typeof model.id === "string" ? model.id : typeof model.name === "string" ? model.name : "") + : ""; + if (modelId && !existingIds.has(modelId)) { + currentModels.push(cloneJson(model)); + existingIds.add(modelId); + } + } + existingCfg.models = currentModels; + } + } + } + + for (const id of selectedIds) { + if (!id.startsWith("plugin:")) continue; + const pkgName = id.slice("plugin:".length); + const row = data.pluginConfigRows.get(pkgName); + if (!row) continue; + const alreadyExists = entries.some( + (entry) => + isPlainObject(entry) && + ((row.id !== undefined && entry.id === row.id) || + (row.name !== undefined && entry.name === row.name)), + ); + if (!alreadyExists) { + entries.push(cloneJson(row)); + } + } + + return entries; +} + +async function runDshPlugin( + command: Command, + profileName: string, + args: string[], + dshHome: string, + env: NodeJS.ProcessEnv, + timeout = 120_000, +): Promise { + await execFileAsync( + command.command, + [...command.prefix, "plugin", "--profile", profileName, ...args], + { + shell: false, + windowsHide: true, + timeout, + maxBuffer: 10 * 1024 * 1024, + encoding: "utf8", + env: buildDshEnv(dshHome, command, env), + }, + ); +} + +/** Reinstall a profile's dependency tree from its manifest and lockfile, as `dsh plugin` repairs it. */ +function installArgs(hasLockfile: boolean): string[] { + return ["install", hasLockfile ? "--frozen-lockfile" : "--config.lockfile=false"]; +} + +function hasDependencies(pkg: Buffer | null | undefined): boolean { + if (!pkg) return false; + try { + const parsed = JSON.parse(pkg.toString("utf8")); + return isPlainObject(parsed?.dependencies) && Object.keys(parsed.dependencies).length > 0; + } catch { + return false; + } +} + +async function applySelectedToProfileDir( + command: Command, + profileName: string, + profileDir: string, + selectedIds: string[], + data: DesktopPatchData, + dshHome: string, + env: NodeJS.ProcessEnv, + progress?: { pluginStart?: (id: string, pkgName: string) => void; pluginsDone?: () => void }, +): Promise { + const patchPath = join(profileDir, "cordis.patch.yml"); + const currentPatch = await readPatchStrict(patchPath); + if (currentPatch.hasJsExpression) { + throw new Error( + "Target profile cordis.patch.yml contains !!js expressions and cannot be modified safely.", + ); + } + + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + for (const id of selectedIds) { + if (!id.startsWith("plugin:")) continue; + const candidate = byId.get(id); + if (!candidate) { + throw new Error(`Selected migration candidate "${id}" was not found in Desktop profile.`); + } + progress?.pluginStart?.(id, candidate.name); + await runDshPlugin(command, profileName, ["add", candidate.spec ?? candidate.providerId], dshHome, env); + } + progress?.pluginsDone?.(); + + const merged = mergePatchEntries(currentPatch.entries, selectedIds, data); + await writeFile(patchPath, stringifyDshPatchYaml(merged), "utf8"); +} + +async function cleanupStaleDryRunDirs(profilesDir: string): Promise { + try { + const entries = await readdir(profilesDir, { withFileTypes: true }); + const now = Date.now(); + for (const entry of entries) { + if (!entry.isDirectory() || !isTemporaryDryRunProfile(entry.name)) continue; + const dir = join(profilesDir, entry.name); + try { + // Only a directory MemCode created and marked is ever removed. + const marker = await readFile(join(dir, DRYRUN_MARKER), "utf8").catch(() => null); + if (marker !== DRYRUN_MARKER_TEXT) continue; + const info = await stat(dir); + if (now - info.mtimeMs > STALE_DRYRUN_AGE_MS) { + await rm(dir, { recursive: true, force: true }); + } + } catch { + /* Ignore transient cleanup failure. */ + } + } + } catch { + /* profilesDir may not exist yet. */ + } +} + +async function assertExistingAcpProfile( + profile: string, + env: NodeJS.ProcessEnv, +): Promise<{ dshHome: string; normalizedTarget: string; targetDir: string }> { + const normalizedTarget = normalizeDshProfile(profile); + const inspected = await inspectDshProfiles(normalizedTarget, env); + if (inspected.activeProfileIssue === "missing") { + throw new Error(`DeepSeek Harness profile "${normalizedTarget}" does not exist.`); + } + if (inspected.activeProfileIssue === "non-acp") { + throw new Error(`DeepSeek Harness profile "${normalizedTarget}" is not an ACP profile.`); + } + return { + dshHome: inspected.dshHome, + normalizedTarget, + targetDir: join(inspected.dshHome, "profiles", normalizedTarget), + }; +} + +/** The provider a dsh catalog entry belongs to: ACP values are JSON `[provider, model]`. */ +function catalogEntry(model: ModelOption): { provider?: string; model: string } { + try { + const parsed = JSON.parse(model.id); + if (Array.isArray(parsed) && parsed.length === 2 && parsed.every((part) => typeof part === "string")) + return { provider: parsed[0], model: parsed[1] }; + } catch { + /* Not a dsh provider tuple. */ + } + return { provider: model.group, model: model.id }; +} + +function sameProvider(provider: string | undefined, providerId: string): boolean { + return ( + provider === providerId || + !!provider?.endsWith(`:${providerId}`) || + !!provider?.endsWith(`/${providerId}`) + ); +} + +/** + * Check that each selected provider really contributes to the catalog: a + * pi-ai provider must list every model it was imported for, and a plugin must + * add at least one model from a provider the baseline did not have. + */ +function unmetExpectations( + ids: string[], + data: DesktopPatchData, + baseline: ModelOption[], + after: ModelOption[], +): DshProviderFailure[] { + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + const entries = after.map((model) => ({ id: model.id, ...catalogEntry(model) })); + const baselineIds = new Set(baseline.map((model) => model.id)); + const baselineProviders = new Set(baseline.map((model) => catalogEntry(model).provider)); + const piAiProviders = ids + .filter((id) => id.startsWith("pi-ai:")) + .map((id) => byId.get(id)?.providerId ?? id.slice("pi-ai:".length)); + const failures: DshProviderFailure[] = []; + for (const id of ids) { + const candidate = byId.get(id); + if (!candidate) continue; + if (candidate.kind === "pi-ai") { + const expected = candidate.missingModels ?? candidate.models; + const listed = (modelId?: string) => + entries.some((entry) => { + if (modelId !== undefined && entry.model !== modelId) return false; + // An entry without provider identity can only vouch for a named model. + if (entry.provider === undefined) return modelId !== undefined; + return sameProvider(entry.provider, candidate.providerId) || entry.provider === candidate.name; + }); + const missing = expected.length ? expected.filter((modelId) => !listed(modelId)) : listed() ? [] : ["any model"]; + if (missing.length) + failures.push({ + id, + name: candidate.name, + reason: `DeepSeek Harness did not list ${missing.join(", ")} for this provider after the import. Check its configuration and API key environment variable in Desktop.`, + }); + } + } + const plugins = ids.filter((id) => byId.get(id)?.kind === "plugin"); + if (plugins.length) { + const added = new Set( + entries + .filter( + (entry) => + !baselineIds.has(entry.id) && + !baselineProviders.has(entry.provider) && + !piAiProviders.some((providerId) => sameProvider(entry.provider, providerId)), + ) + .map((entry) => entry.provider ?? entry.id), + ); + if (added.size < plugins.length) + for (const id of plugins) + failures.push({ + id, + name: byId.get(id)?.name ?? id, + reason: + plugins.length === 1 + ? "The plugin installed, but DeepSeek Harness listed no new models from it. Configure its provider in Desktop first." + : `The selected plugins added models from ${added.size} new provider${added.size === 1 ? "" : "s"}, not ${plugins.length}.`, + }); + } + return failures; +} + +function defaultProbe(options?: { probe?: StrictAcpProbe }): StrictAcpProbe { + return ( + options?.probe ?? + ((profile, cmd) => + probeStandardCatalog("dsh", cmd, profile, { strictStdout: true, allowStaging: true })) + ); +} + +export async function dryRunDshMigration( + command: Command, + targetProfile: string, + selectedIds: string[], + options?: { env?: NodeJS.ProcessEnv; probe?: StrictAcpProbe }, +): Promise { + const env = options?.env ?? process.env; + const { dshHome, normalizedTarget, targetDir } = await assertExistingAcpProfile(targetProfile, env); + const profilesDir = join(dshHome, "profiles"); + await cleanupStaleDryRunDirs(profilesDir); + + const probeCmd = withDshHomeCommand(command, dshHome, env); + const probe = defaultProbe(options); + const ids = [...new Set(selectedIds)]; + + if (ids.length === 0) { + const previewModels = await probe(normalizedTarget, probeCmd); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: [], + failed: [], + previewModels, + }; + } + + const profileFailure = (reason: string): DshDryRunResult => ({ + ok: false, + targetProfile: normalizedTarget, + passedIds: [], + failed: [{ id: `profile:${normalizedTarget}`, name: normalizedTarget, reason }], + previewModels: [], + error: reason, + }); + + // The fingerprint and every staging copy come from the same bytes. + let snapshot: ProfileSnapshot; + try { + snapshot = await readProfileSnapshot(targetDir); + } catch (error) { + return profileFailure(extractErrorMessage(error)); + } + const data = await computeDesktopDiff(normalizedTarget, env); + const stale = staleSelections(ids, data); + if (stale.length) { + return { + ok: false, + targetProfile: normalizedTarget, + passedIds: [], + failed: stale, + previewModels: [], + error: "Some selected providers are no longer offered by DeepSeek Harness Desktop.", + }; + } + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + const targetHasDependencies = hasDependencies(snapshot.get("package.json")); + + const runStaging = async (stagedIds: string[]): Promise => { + const stagingName = `memcode-dryrun-${randomBytes(4).toString("hex")}`; + const stagingDir = join(profilesDir, stagingName); + await mkdir(stagingDir, { recursive: true }); + await writeFile(join(stagingDir, DRYRUN_MARKER), DRYRUN_MARKER_TEXT, "utf8"); + try { + for (const [file, content] of snapshot) { + if (content !== null) await writeFile(join(stagingDir, file), content); + } + // A profile's third-party bundles load from its own node_modules. Build + // an independent tree in staging; `plugin add` installs it as well. + if (targetHasDependencies && !stagedIds.some((id) => id.startsWith("plugin:"))) { + await runDshPlugin( + command, + stagingName, + installArgs(snapshot.get("pnpm-lock.yaml") != null), + dshHome, + env, + ); + } + if (stagedIds.length > 0) { + await applySelectedToProfileDir(command, stagingName, stagingDir, stagedIds, data, dshHome, env); + } + return await probe(stagingName, probeCmd); + } finally { + await rm(stagingDir, { recursive: true, force: true }).catch(() => {}); + } + }; + + // An already broken profile is a profile failure, never blamed on providers. + let baseline: ModelOption[]; + try { + baseline = await runStaging([]); + } catch (baselineError) { + return profileFailure( + `Existing ACP profile failed validation before applying Desktop providers: ${extractErrorMessage(baselineError)}`, + ); + } + + const attempt = async (stagedIds: string[]): Promise<{ models: ModelOption[]; failures: DshProviderFailure[] }> => { + const models = await runStaging(stagedIds); + return { models, failures: unmetExpectations(stagedIds, data, baseline, models) }; + }; + + let combinedError: string; + try { + const combined = await attempt(ids); + if (combined.failures.length === 0) { + const baselineIds = new Set(baseline.map((model) => model.id)); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: ids, + failed: [], + previewModels: combined.models, + plan: { + fingerprint: migrationFingerprint(normalizedTarget, ids, data, snapshot), + targetProfile: normalizedTarget, + selectedIds: ids, + expectedModelIds: combined.models + .map((model) => model.id) + .filter((id) => !baselineIds.has(id)), + }, + }; + } + combinedError = combined.failures.map((failure) => `${failure.name}: ${failure.reason}`).join(" "); + } catch (error) { + combinedError = extractErrorMessage(error); + } + + const passedIds: string[] = []; + const failed: DshProviderFailure[] = []; + for (const id of ids) { + const candidate = candidateMap.get(id); + try { + const single = await attempt([id]); + if (single.failures.length) failed.push(...single.failures); + else passedIds.push(id); + } catch (error) { + failed.push({ + id, + name: candidate?.name ?? id, + reason: extractErrorMessage(error), + }); + } + } + const combinationError = + failed.length === 0 + ? `Selected providers passed individually but failed when combined: ${combinedError}` + : undefined; + return { + ok: false, + targetProfile: normalizedTarget, + passedIds, + failed, + previewModels: [], + ...(combinationError ? { error: combinationError } : {}), + }; +} + +export interface DshApplyResult { + ok: boolean; + appliedIds: string[]; + failed: DshProviderFailure[]; + models: ModelOption[]; + error?: string; + /** False when rollback could not restore the profile; it may need manual recovery. */ + restored?: boolean; +} + +export async function applyDshMigration( + command: Command, + plan: DshMigrationPlan, + options?: { env?: NodeJS.ProcessEnv; probe?: StrictAcpProbe }, +): Promise { + const env = options?.env ?? process.env; + const { dshHome, normalizedTarget, targetDir } = await assertExistingAcpProfile(plan.targetProfile, env); + const probeCmd = withDshHomeCommand(command, dshHome, env); + const probe = defaultProbe(options); + const selectedIds = plan.selectedIds; + const profileId = `profile:${normalizedTarget}`; + const refuse = (reason: string): DshApplyResult => ({ + ok: false, + appliedIds: [], + failed: [{ id: profileId, name: normalizedTarget, reason }], + models: [], + error: reason, + restored: true, + }); + + if (normalizedTarget !== plan.targetProfile || selectedIds.length === 0) + return refuse("Test the selected providers before importing them."); + + let snapshots: ProfileSnapshot; + try { + snapshots = await readProfileSnapshot(targetDir); + } catch (error) { + return refuse(`${extractErrorMessage(error)}. The profile was not modified.`); + } + const data = await computeDesktopDiff(normalizedTarget, env); + if ( + staleSelections(selectedIds, data).length > 0 || + migrationFingerprint(normalizedTarget, selectedIds, data, snapshots) !== plan.fingerprint + ) + return refuse( + "DeepSeek Harness Desktop or this profile changed after the dry-run. Test the selected providers again before importing them.", + ); + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + + const selectedPlugins = selectedIds + .filter((id) => id.startsWith("plugin:")) + .map((id) => id.slice("plugin:".length)); + const preExistingPlugins = new Set(); + for (const pkgName of selectedPlugins) { + if (await isDirectory(join(targetDir, "node_modules", ...pkgName.split("/")))) { + preExistingPlugins.add(pkgName); + } + } + + // A failure is the profile's until a specific plugin is being installed. + let activeId = profileId; + let activeName = normalizedTarget; + let dependenciesTouched = false; + try { + await applySelectedToProfileDir( + command, + normalizedTarget, + targetDir, + selectedIds, + data, + dshHome, + env, + { + pluginStart: (id, name) => { + activeId = id; + activeName = candidateMap.get(id)?.name ?? name; + dependenciesTouched = true; + }, + pluginsDone: () => { + activeId = profileId; + activeName = normalizedTarget; + }, + }, + ); + const models = await probe(normalizedTarget, probeCmd); + const listed = new Set(models.map((model) => model.id)); + const missing = plan.expectedModelIds.filter((id) => !listed.has(id)); + if (missing.length > 0) + throw new Error( + `After the import DeepSeek Harness did not list ${missing.length} model${missing.length === 1 ? "" : "s"} the dry-run verified: ${missing.join(", ")}.`, + ); + return { + ok: true, + appliedIds: [...selectedIds], + failed: [], + models, + }; + } catch (error) { + const rollbackErrors: string[] = []; + for (const [file, content] of snapshots) { + const path = join(targetDir, file); + try { + if (content === null) { + await rm(path, { force: true }); + } else { + await writeFile(path, content); + } + } catch (rbError) { + rollbackErrors.push(`${file}: ${extractErrorMessage(rbError)}`); + } + } + if (dependenciesTouched) { + for (const pkgName of selectedPlugins) { + if (!preExistingPlugins.has(pkgName)) { + try { + await rm(join(targetDir, "node_modules", ...pkgName.split("/")), { + recursive: true, + force: true, + }); + } catch (rbError) { + rollbackErrors.push(`node_modules/${pkgName}: ${extractErrorMessage(rbError)}`); + } + } + } + // `plugin add` can also change existing and transitive dependencies. + // Reinstall the restored lockfile, as dsh itself does after a rejected add. + if (rollbackErrors.length === 0) { + try { + await runDshPlugin( + command, + normalizedTarget, + installArgs(snapshots.get("pnpm-lock.yaml") != null), + dshHome, + env, + 300_000, + ); + } catch (rbError) { + rollbackErrors.push( + `node_modules could not be reinstalled (${extractErrorMessage(rbError)}); run "dsh plugin --profile ${normalizedTarget} install"`, + ); + } + } + } + const reason = extractErrorMessage(error); + if (rollbackErrors.length > 0) { + const recoveryDir = join( + dshHome, + "memcode-recovery", + `${normalizedTarget}-${Date.now()}-${randomBytes(3).toString("hex")}`, + ); + let recoveryNote = ""; + try { + await mkdir(recoveryDir, { recursive: true }); + for (const [file, content] of snapshots) { + if (content !== null) { + await writeFile(join(recoveryDir, file), content); + } + } + recoveryNote = ` Recovery snapshots saved to ${recoveryDir}.`; + } catch (backupError) { + recoveryNote = ` Could not write recovery snapshots (${extractErrorMessage(backupError)}).`; + } + const fullError = `Migration failed (${reason}) and rollback could not restore all files (${rollbackErrors.join("; ")}).${recoveryNote}`; + return { + ok: false, + appliedIds: [], + failed: [{ id: activeId, name: activeName, reason: fullError }], + models: [], + error: fullError, + restored: false, + }; + } + return { + ok: false, + appliedIds: [], + failed: [ + { + id: activeId, + name: activeName, + reason, + }, + ], + models: [], + error: reason, + restored: true, + }; + } +} diff --git a/runtime/dsh-profiles.ts b/runtime/dsh-profiles.ts new file mode 100644 index 0000000..cb3e2ce --- /dev/null +++ b/runtime/dsh-profiles.ts @@ -0,0 +1,262 @@ +import { execFile } from "node:child_process"; +import { readdir, readFile, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import type { DshProfileSummary } from "../src/shared"; +import { childEnv, exists, type Command } from "./commands"; +import { parseDshPatchYaml } from "./dsh-yaml"; + +const execFileAsync = promisify(execFile); + +export const defaultDshProfile = "acp"; + +const PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const CONFLICTING_APP_BUNDLES = new Set([ + "@deepseek-ai/dsh-web-app", + "@deepseek-ai/dsh-sdk-app", + "@deepseek-ai/dsh-tui-app", + "@deepseek-ai/dsh-headless-app", +]); + +export function resolveDshHome(env: NodeJS.ProcessEnv = process.env): string { + return env.DSH_HOME?.trim() || join(homedir(), ".dsh"); +} + +export function normalizeDshProfile( + value?: string, + options?: { allowStaging?: boolean }, +): string { + const trimmed = value?.trim(); + if (!trimmed) return defaultDshProfile; + if (trimmed.toLowerCase() === "desktop") { + throw new Error('Profile name "desktop" is reserved for DeepSeek Harness Desktop and cannot be used as an ACP profile.'); + } + if (trimmed.toLowerCase() === "node_modules") { + throw new Error('Profile name "node_modules" is reserved and cannot be used as an ACP profile.'); + } + if (!options?.allowStaging && isTemporaryDryRunProfile(trimmed)) { + throw new Error(`Profile name "${trimmed}" is reserved for MemCode temporary dry-run staging.`); + } + if (!PROFILE_NAME_RE.test(trimmed)) { + throw new Error( + `Invalid DeepSeek Harness profile name "${trimmed}". Use 1-64 characters matching [A-Za-z0-9._-], starting with a letter or digit.`, + ); + } + return trimmed; +} + +export function isTemporaryDryRunProfile(name: string): boolean { + return /^memcode-dryrun-[a-f0-9]+$/i.test(name); +} + +/** A directory name MemCode can pass to `dsh --profile` as a user profile. */ +function isSelectableProfileName(name: string): boolean { + try { + return normalizeDshProfile(name) === name; + } catch { + return false; + } +} + +function patchInsertsAcp(entries: unknown[]): boolean { + for (const entry of entries) { + if (!entry || typeof entry !== "object") continue; + const insert = (entry as Record).insert; + if (!Array.isArray(insert)) continue; + for (const item of insert) { + if (item === "@deepseek-ai/dsh-acp") return true; + if (item && typeof item === "object" && (item as Record).name === "@deepseek-ai/dsh-acp") { + return true; + } + } + } + return false; +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} + +async function classifyProfileDir(profileDir: string, name: string): Promise { + let pkg: { dependencies?: Record; dsh?: { profile?: { bundles?: unknown[] } } } = {}; + try { + pkg = JSON.parse(await readFile(join(profileDir, "package.json"), "utf8")); + } catch { + /* Missing or unreadable package.json; treat as empty. */ + } + + let patchEntries: unknown[] = []; + try { + patchEntries = parseDshPatchYaml(await readFile(join(profileDir, "cordis.patch.yml"), "utf8")).entries; + } catch { + /* Missing or unreadable cordis.patch.yml; treat as empty. */ + } + + const bundles = Array.isArray(pkg.dsh?.profile?.bundles) + ? pkg.dsh.profile.bundles.filter((b): b is string => typeof b === "string") + : []; + const hasAcp = bundles.includes("@deepseek-ai/dsh-acp-app") || patchInsertsAcp(patchEntries); + const hasConflict = bundles.some((bundle) => CONFLICTING_APP_BUNDLES.has(bundle)); + const hasCustomConfig = + Object.keys(pkg.dependencies ?? {}).length > 0 || patchEntries.length > 0; + + return { + name, + kind: hasAcp && !hasConflict ? "acp" : "non-acp", + hasCustomConfig, + }; +} + +export interface DshProfilesInspection { + dshHome: string; + activeProfile: string; + configuredProfile?: string; + recommendedProfile?: string; + activeProfileIssue?: "missing" | "non-acp"; + acpProfiles: DshProfileSummary[]; + nonAcpProfiles: DshProfileSummary[]; + desktopProfilePresent: boolean; + needsProfileCreation: boolean; +} + +export async function inspectDshProfiles( + configuredProfile?: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + const dshHome = resolveDshHome(env); + const profilesDir = join(dshHome, "profiles"); + const desktopProfilePresent = await isDirectory(join(profilesDir, "desktop")); + + const acpProfiles: DshProfileSummary[] = []; + const nonAcpProfiles: DshProfileSummary[] = []; + + try { + const entries = await readdir(profilesDir, { withFileTypes: true }); + for (const entry of entries) { + const name = entry.name; + // Desktop, node_modules, staging and names dsh cannot be given (such as + // "acp copy" or "_backup") are never offered or selected automatically. + if (!isSelectableProfileName(name)) continue; + const fullPath = join(profilesDir, name); + if (!entry.isDirectory() && !(await isDirectory(fullPath))) continue; + const summary = await classifyProfileDir(fullPath, name); + if (summary.kind === "acp") acpProfiles.push(summary); + else nonAcpProfiles.push(summary); + } + } catch { + /* $DSH_HOME/profiles may not exist yet. */ + } + + acpProfiles.sort((a, b) => a.name.localeCompare(b.name)); + nonAcpProfiles.sort((a, b) => a.name.localeCompare(b.name)); + + const acpDefault = acpProfiles.find((p) => p.name === defaultDshProfile); + const customAcp = acpProfiles.find((p) => p.hasCustomConfig); + const recommendedProfile = + customAcp && (!acpDefault || !acpDefault.hasCustomConfig) + ? customAcp.name + : acpDefault?.name ?? acpProfiles[0]?.name; + + const trimmedConfigured = configuredProfile?.trim(); + if (trimmedConfigured) { + const normalized = normalizeDshProfile(trimmedConfigured); + const inAcp = acpProfiles.find((p) => p.name === normalized); + const inNonAcp = nonAcpProfiles.find((p) => p.name === normalized); + return { + dshHome, + activeProfile: normalized, + configuredProfile: normalized, + ...(recommendedProfile ? { recommendedProfile } : {}), + ...(!inAcp + ? { activeProfileIssue: inNonAcp ? ("non-acp" as const) : ("missing" as const) } + : {}), + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: acpProfiles.length === 0, + }; + } + + if (customAcp && (!acpDefault || !acpDefault.hasCustomConfig)) { + return { + dshHome, + activeProfile: customAcp.name, + recommendedProfile: customAcp.name, + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: false, + }; + } + + if (acpProfiles.length > 0) { + const active = acpDefault?.name ?? acpProfiles[0].name; + return { + dshHome, + activeProfile: active, + ...(recommendedProfile ? { recommendedProfile } : {}), + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: false, + }; + } + + // An existing "acp" directory that is not ACP must not be launched as one. + const defaultIsNonAcp = nonAcpProfiles.some((p) => p.name === defaultDshProfile); + return { + dshHome, + activeProfile: defaultDshProfile, + ...(defaultIsNonAcp ? { activeProfileIssue: "non-acp" as const } : {}), + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: true, + }; +} + +export async function createDshAcpProfile( + command: Command, + name: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + const normalized = normalizeDshProfile(name); + const targetName = normalized.toLowerCase() === defaultDshProfile ? defaultDshProfile : normalized; + const dshHome = resolveDshHome(env); + const profileDir = join(dshHome, "profiles", targetName); + + if (await exists(profileDir)) { + throw new Error(`DeepSeek Harness profile "${targetName}" already exists.`); + } + + // dsh rejects --from-default-profile for shipped profile names like "acp". + const args = + targetName === defaultDshProfile + ? [...command.prefix, "--profile", defaultDshProfile, "--dump-config"] + : [...command.prefix, "--profile", targetName, "--from-default-profile", defaultDshProfile, "--dump-config"]; + + await execFileAsync(command.command, args, { + shell: false, + windowsHide: true, + timeout: 30_000, + maxBuffer: 10 * 1024 * 1024, + encoding: "utf8", + env: { + ...childEnv(), + ...command.env, + ...(env !== process.env ? env : {}), + DSH_HOME: dshHome, + }, + }); + + const inspected = await inspectDshProfiles(targetName, env); + if (!inspected.acpProfiles.some((p) => p.name === targetName)) { + throw new Error(`Created profile "${targetName}" did not produce a valid DeepSeek Harness ACP profile.`); + } + return targetName; +} diff --git a/runtime/dsh-setup-gate.ts b/runtime/dsh-setup-gate.ts new file mode 100644 index 0000000..3773dd9 --- /dev/null +++ b/runtime/dsh-setup-gate.ts @@ -0,0 +1,73 @@ +/** + * Coordinates DeepSeek Harness setup changes with the separate dsh processes + * that read the profile. Setup does not start while a dsh reviewer or planner + * runs, and none of them starts while setup may be rewriting the profile. + * Shutdown waits for a running setup so its verification or rollback finishes. + */ +export class DshSetupGate { + private current: { operation: string; mutates: boolean; done: Promise } | null = null; + private readers = 0; + private closed = false; + + /** The setup operation in progress, if any. */ + get operation(): string | null { + return this.current?.operation ?? null; + } + + /** Whether the running operation may rewrite the profile or the CLI. */ + get mutating(): boolean { + return this.current?.mutates === true; + } + + /** + * Admit one dsh process that reads the profile. Call the returned function + * once the process has exited. + */ + admit(activity = "review"): () => void { + if (this.mutating) + throw new Error( + `Wait for DeepSeek Harness setup to finish before starting a DeepSeek Harness ${activity}.`, + ); + this.readers++; + let released = false; + return () => { + if (released) return; + released = true; + this.readers--; + }; + } + + /** + * Run one setup operation. Operations never overlap; one that `mutates` + * also waits for no dsh reader and keeps new readers out until it settles. + */ + async run( + operation: string, + fn: () => Promise, + { mutates = true }: { mutates?: boolean } = {}, + ): Promise { + if (this.closed) throw new Error("MemCode is shutting down. Try again after it restarts."); + if (this.current) + throw new Error( + "Another DeepSeek Harness setup operation is already in progress. Wait for it to finish.", + ); + if (mutates && this.readers > 0) + throw new Error( + "Wait for the DeepSeek Harness review or plan in progress to finish before changing its setup.", + ); + let settle!: () => void; + this.current = { operation, mutates, done: new Promise((resolve) => (settle = resolve)) }; + try { + return await fn(); + } finally { + this.current = null; + settle(); + } + } + + /** Refuse new setup operations and wait for a running one to finish. */ + async close(): Promise { + this.closed = true; + while (this.current) await this.current.done; + } +} diff --git a/runtime/dsh-yaml.ts b/runtime/dsh-yaml.ts new file mode 100644 index 0000000..d652159 --- /dev/null +++ b/runtime/dsh-yaml.ts @@ -0,0 +1,842 @@ +/** Set on a value that is itself tagged `!!js`, or that contains one that is. */ +const JS_EXPR = Symbol("dsh.jsExpression"); +/** Set only on a collection that carries an explicit `!!js` tag of its own. */ +const JS_EXPLICIT = Symbol("dsh.jsExplicitTag"); + +function markJsExpr(value: T): T { + if (value && typeof value === "object") { + Object.defineProperty(value, JS_EXPR, { value: true, enumerable: false, configurable: true }); + } + return value; +} + +function markExplicitJs(value: T): T { + if (value && typeof value === "object") { + markJsExpr(value); + Object.defineProperty(value, JS_EXPLICIT, { value: true, enumerable: false, configurable: true }); + } + return value; +} + +export function hasJsTag(value: unknown): boolean { + if (!value || typeof value !== "object") return false; + if ((value as Record)[JS_EXPR] === true) return true; + if (Array.isArray(value)) return value.some((item) => hasJsTag(item)); + return Object.values(value).some((item) => hasJsTag(item)); +} + +/** + * Whether this collection itself was written with an explicit `!!js` tag. + * Unlike {@link hasJsTag}, a marker propagated from a tagged descendant does + * not count, so safe siblings of a tagged value stay distinguishable. + */ +export function hasExplicitJsTag(value: unknown): boolean { + return ( + !!value && + typeof value === "object" && + (value as Record)[JS_EXPLICIT] === true + ); +} + +const SECRET_VALUE_RE = /^(?:Bearer|Basic)\s+\S+/i; +const SECRET_HEAD_WORDS = new Set([ + "secret", + "password", + "passwd", + "passphrase", + "pwd", + "token", + "authorization", + "auth", + "cookie", + "cookies", + "credential", + "credentials", + "apikey", + "privatekey", +]); +const SECRET_KEY_QUALIFIERS = new Set([ + "api", + "private", + "access", + "secret", + "signing", + "session", + "encryption", + "client", + "license", + "subscription", +]); + +function keyWords(key: string): string[] { + return key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean); +} + +/** + * A key whose value is itself a credential. The head noun decides, so + * `accessToken` and `privateKey` count while `maxTokens`, `tokenLimit` and the + * `apiKeyEnv` indirection (the name of an environment variable) do not. + */ +function isCredentialKey(key: string): boolean { + const words = keyWords(key); + const head = words.at(-1); + if (!head || head === "env") return false; + if (SECRET_HEAD_WORDS.has(head)) return true; + return head === "key" && (words.length === 1 || SECRET_KEY_QUALIFIERS.has(words[words.length - 2])); +} + +function hasNonEmptyCredentialValue(value: unknown): boolean { + if (typeof value === "string") return value.trim().length > 0; + if (typeof value === "number" || typeof value === "bigint") return true; + if (typeof value === "boolean") return value; + if (Array.isArray(value)) return value.some((item) => hasNonEmptyCredentialValue(item)); + if (value && typeof value === "object") { + return Object.values(value).some((item) => hasNonEmptyCredentialValue(item)); + } + return false; +} + +export function hasInlineSecret(obj: unknown): boolean { + if (typeof obj === "string") return SECRET_VALUE_RE.test(obj.trim()); + if (!obj || typeof obj !== "object") return false; + if (Array.isArray(obj)) return obj.some((item) => hasInlineSecret(item)); + for (const [key, value] of Object.entries(obj)) { + if (isCredentialKey(key) && hasNonEmptyCredentialValue(value)) return true; + if (hasInlineSecret(value)) return true; + } + return false; +} + +function stripInlineComment(line: string): string { + let quote: "'" | '"' | null = null; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") { + if (line[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + return line.slice(0, i).replace(/\s+$/, ""); + } + } + return line.replace(/\s+$/, ""); +} + +function countIndent(line: string): number { + let i = 0; + while (i < line.length && line[i] === " ") i++; + return i; +} + +function findUnquotedColon(text: string, allowTightQuotedColon = false): number { + let quote: "'" | '"' | null = null; + let depth = 0; + let justClosedQuote = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === "'") { + if (ch === "'") { + if (text[i + 1] === "'") i++; + else { + quote = null; + justClosedQuote = depth === 0; + } + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') { + quote = null; + justClosedQuote = depth === 0; + } + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + justClosedQuote = false; + continue; + } + if (ch === "[" || ch === "{") { + depth++; + justClosedQuote = false; + } else if ((ch === "]" || ch === "}") && depth > 0) { + depth--; + justClosedQuote = false; + } else if ( + ch === ":" && + depth === 0 && + (i + 1 === text.length || /\s/.test(text[i + 1]) || (allowTightQuotedColon && justClosedQuote)) + ) { + return i; + } else if (!/\s/.test(ch)) { + justClosedQuote = false; + } + } + return -1; +} + +/** + * A quoted scalar, or `undefined` when the text is not one. Text that opens a + * quote without being exactly one quoted scalar is rejected rather than read as + * a plain string that dsh would parse differently. + */ +function quotedScalar(trimmed: string): string | undefined { + const quote = trimmed[0]; + if (quote !== "'" && quote !== '"') return undefined; + const inner = trimmed.slice(1, -1); + if (trimmed.length >= 2 && trimmed.endsWith(quote)) { + if (quote === "'" && !/'/.test(inner.replace(/''/g, ""))) return inner.replace(/''/g, "'"); + if (quote === '"' && !/"/.test(inner.replace(/\\[\s\S]/g, ""))) return unescapeDoubleQuoted(inner); + } + throw new Error("Unsupported multi-line or malformed quoted YAML scalar in cordis.patch.yml."); +} + +const ESCAPES: Readonly> = { + "0": "\0", + a: "\x07", + b: "\b", + t: "\t", + "\t": "\t", + n: "\n", + v: "\v", + f: "\f", + r: "\r", + e: "\x1b", + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + N: "\x85", + _: "\xa0", + L: "\u2028", + P: "\u2029", +}; + +function unescapeDoubleQuoted(raw: string): string { + return raw.replace(/\\(x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|[\s\S])/g, (_, seq: string) => { + if (seq.length === 1) { + if (Object.prototype.hasOwnProperty.call(ESCAPES, seq)) return ESCAPES[seq]; + throw new Error(`Unsupported YAML escape "\\${seq}" in cordis.patch.yml.`); + } + const code = Number.parseInt(seq.slice(1), 16); + if (code > 0x10ffff) throw new Error("Invalid YAML unicode escape in cordis.patch.yml."); + return String.fromCodePoint(code); + }); +} + +/** + * Resolve a plain (unquoted) scalar the way dsh's YAML 1.2 core schema does, + * so a value keeps its type when MemCode rewrites the patch. Plain forms whose + * type MemCode cannot reproduce exactly are refused instead of guessed. + */ +function resolvePlain(text: string): unknown { + if (text === "" || /^(?:~|null|Null|NULL)$/.test(text)) return null; + if (/^(?:true|True|TRUE)$/.test(text)) return true; + if (/^(?:false|False|FALSE)$/.test(text)) return false; + if (/^[-+]?[0-9]+$/.test(text)) return Number(text); + const radix = /^([-+]?)0(x[0-9a-fA-F]+|o[0-7]+|b[01]+)$/.exec(text); + if (radix) { + const value = Number.parseInt(radix[2].slice(1), { x: 16, o: 8, b: 2 }[radix[2][0] as "x" | "o" | "b"]); + return radix[1] === "-" ? -value : value; + } + if (/^[-+]?[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/.test(text) || /^\.[0-9]+(?:[eE][-+]?[0-9]+)?$/.test(text)) { + return Number(text); + } + if (/^[-+]?\.(?:inf|Inf|INF)$/.test(text)) return text.startsWith("-") ? -Infinity : Infinity; + if (/^\.(?:nan|NaN|NAN)$/.test(text)) return Number.NaN; + // Underscore digit separators and timestamps load as numbers or dates in + // dsh, with edge rules MemCode does not reproduce. + if ( + (text.includes("_") && + (/^[-+]?[0-9][0-9_]*(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?$/.test(text) || + /^\.[0-9_]+(?:[eE][-+]?[0-9]+)?$/.test(text) || + /^[-+]?0[xob][0-9a-fA-F_]+$/.test(text))) || + /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}(?:$|[Tt ])/.test(text) + ) { + throw new Error(`Unsupported YAML scalar "${text}" in cordis.patch.yml.`); + } + return text; +} + +function unquoteKey(raw: string): string { + const trimmed = raw.trim(); + const quoted = quotedScalar(trimmed); + if (quoted !== undefined) return quoted; + // dsh resolves a plain key's type first and then uses its string form. + const resolved = resolvePlain(trimmed); + return resolved === null ? "null" : String(resolved); +} + +function assertSupportedYamlToken(trimmed: string): void { + if (/^&[^\s,\]}]+/.test(trimmed) || /^\*[^\s,\]}]+/.test(trimmed)) { + throw new Error("YAML anchors and aliases are not supported in cordis.patch.yml."); + } + if (/^![^!]|^!!(?!js(?:\/[A-Za-z0-9_-]+)?(?:\s|$))/i.test(trimmed)) { + throw new Error("Unsupported YAML tag in cordis.patch.yml."); + } +} + +function parseScalar(raw: string, ctx: { hasJsExpression: boolean }): { value: unknown; taggedJs: boolean } { + let trimmed = raw.trim(); + let taggedJs = false; + const jsMatch = /^!!js(?:\/[A-Za-z0-9_-]+)?(?:\s+([\s\S]*))?$/.exec(trimmed); + if (jsMatch) { + ctx.hasJsExpression = true; + taggedJs = true; + trimmed = (jsMatch[1] ?? "").trim(); + if (!trimmed) return { value: undefined, taggedJs: true }; + } + assertSupportedYamlToken(trimmed); + const quoted = quotedScalar(trimmed); + if (quoted !== undefined) return { value: quoted, taggedJs }; + return { value: resolvePlain(trimmed), taggedJs }; +} + +function splitFlowItems(inner: string): string[] { + const items: string[] = []; + let start = 0; + let quote: "'" | '"' | null = null; + let depth = 0; + for (let i = 0; i < inner.length; i++) { + const ch = inner[i]; + if (quote === "'") { + if (ch === "'") { + if (inner[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (ch === "[" || ch === "{") depth++; + else if ((ch === "]" || ch === "}") && depth > 0) depth--; + else if (ch === "," && depth === 0) { + items.push(inner.slice(start, i)); + start = i + 1; + } + } + const tail = inner.slice(start); + if (tail.trim()) items.push(tail); + return items; +} + +function parseFlow(text: string, ctx: { hasJsExpression: boolean }): { value: unknown; taggedJs: boolean } { + let trimmed = text.trim(); + let taggedJs = false; + const jsMatch = /^!!js(?:\/[A-Za-z0-9_-]+)?(?:\s+([\s\S]*))?$/.exec(trimmed); + if (jsMatch) { + ctx.hasJsExpression = true; + taggedJs = true; + trimmed = (jsMatch[1] ?? "").trim(); + } + const mark = (value: T, anyJs: boolean): T => + taggedJs ? markExplicitJs(value) : anyJs ? markJsExpr(value) : value; + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + const inner = trimmed.slice(1, -1).trim(); + if (!inner) { + const arr: unknown[] = []; + return { value: mark(arr, false), taggedJs }; + } + let anyJs = taggedJs; + const arr = splitFlowItems(inner).map((item) => { + const res = parseFlow(item, ctx); + if (res.taggedJs) anyJs = true; + return res.value; + }); + return { value: mark(arr, anyJs), taggedJs: anyJs }; + } + if (trimmed.startsWith("{") && trimmed.endsWith("}")) { + const inner = trimmed.slice(1, -1).trim(); + const obj: Record = {}; + if (!inner) return { value: mark(obj, false), taggedJs }; + let anyJs = taggedJs; + for (const part of splitFlowItems(inner)) { + const colon = findUnquotedColon(part, true); + if (colon === -1) { + throw new Error("Unsupported or malformed YAML flow mapping entry in cordis.patch.yml."); + } + const key = unquoteKey(part.slice(0, colon)); + if (key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + const res = parseFlow(part.slice(colon + 1), ctx); + if (res.taggedJs) anyJs = true; + obj[key] = res.value; + } + return { value: mark(obj, anyJs), taggedJs: anyJs }; + } + const scalar = parseScalar(trimmed, ctx); + return { value: scalar.value, taggedJs: taggedJs || scalar.taggedJs }; +} + +function isFlowComplete(text: string): boolean { + let quote: "'" | '"' | null = null; + let depth = 0; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === "'") { + if (ch === "'") { + if (text[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') quote = ch; + else if (ch === "[" || ch === "{") depth++; + else if ((ch === "]" || ch === "}") && depth > 0) depth--; + } + return quote === null && depth === 0; +} + +class YamlParser { + readonly lines: string[]; + index = 0; + hasJsExpression = false; + + constructor(text: string) { + this.lines = text.replace(/\r\n?/g, "\n").split("\n"); + } + + private skipIgnorable(): void { + while (this.index < this.lines.length) { + const cleaned = stripInlineComment(this.lines[this.index]); + if (cleaned.trim() === "") this.index++; + else break; + } + } + + private peekContent(): { indent: number; text: string } | null { + this.skipIgnorable(); + if (this.index >= this.lines.length) return null; + const cleaned = stripInlineComment(this.lines[this.index]); + return { indent: countIndent(cleaned), text: cleaned.trimStart() }; + } + + private parseBlockScalar(header: string, parentIndent: number): string { + const style = header[0] as "|" | ">"; + const rest = header.slice(1).trim(); + const chomp = rest.includes("-") ? "-" : rest.includes("+") ? "+" : ""; + const indentDigit = /\d+/.exec(rest)?.[0]; + let contentIndent = indentDigit ? parentIndent + Number.parseInt(indentDigit, 10) : -1; + const rawLines: string[] = []; + + while (this.index < this.lines.length) { + const line = this.lines[this.index]; + const indent = countIndent(line); + if (line.trim() === "") { + rawLines.push(""); + this.index++; + continue; + } + if (contentIndent === -1) { + if (indent <= parentIndent) break; + contentIndent = indent; + } else if (indent < contentIndent) { + break; + } + rawLines.push(line.slice(contentIndent)); + this.index++; + } + + let trailingEmpty = 0; + while (trailingEmpty < rawLines.length && rawLines[rawLines.length - 1 - trailingEmpty] === "") { + trailingEmpty++; + } + const contentLines = rawLines.slice(0, rawLines.length - trailingEmpty); + + let body: string; + if (style === "|") { + body = contentLines.join("\n"); + } else { + // Folding joins two adjacent normal lines with a space. A line that is + // more indented keeps its surrounding line breaks, and each empty line + // between two normal lines stands for one line break. + let previous: "normal" | "more" | null = null; + let empty = 0; + body = ""; + for (const line of contentLines) { + if (line === "") { + empty++; + continue; + } + const kind = /^[ \t]/.test(line) ? "more" : "normal"; + if (previous === null) body += "\n".repeat(empty); + else if (previous === "normal" && kind === "normal") body += empty ? "\n".repeat(empty) : " "; + else body += "\n".repeat(empty + 1); + body += line; + previous = kind; + empty = 0; + } + } + + if (contentLines.length === 0) return chomp === "+" ? "\n".repeat(trailingEmpty) : ""; + if (chomp === "-") return body; + return body + "\n" + (chomp === "+" ? "\n".repeat(trailingEmpty) : ""); + } + + private collectFlow(firstPart: string): string { + let acc = firstPart; + while (!isFlowComplete(acc) && this.index < this.lines.length) { + const next = stripInlineComment(this.lines[this.index++]).trim(); + if (next) acc += " " + next; + } + if (!isFlowComplete(acc)) { + throw new Error("Incomplete YAML flow collection in cordis.patch.yml."); + } + return acc; + } + + private parseValue(rawVal: string, parentIndent: number): { value: unknown; taggedJs: boolean } { + const val = rawVal.trim(); + assertSupportedYamlToken(val); + const jsOnly = /^!!js(?:\/[A-Za-z0-9_-]+)?$/.exec(val); + if (jsOnly) { + this.hasJsExpression = true; + const next = this.peekContent(); + if (next && next.indent > parentIndent) { + const parsed = this.parseBlock(next.indent); + return { value: markExplicitJs(parsed.value ?? {}), taggedJs: true }; + } + return { value: undefined, taggedJs: true }; + } + const jsPrefixed = /^!!js(?:\/[A-Za-z0-9_-]+)?\s+([\s\S]+)$/.exec(val); + if (jsPrefixed) { + this.hasJsExpression = true; + const inner = jsPrefixed[1].trim(); + if (/^[|>][+-]?\d*$/.test(inner)) { + return { value: this.parseBlockScalar(inner, parentIndent), taggedJs: true }; + } + if (inner.startsWith("[") || inner.startsWith("{")) { + const res = parseFlow(this.collectFlow(inner), this); + return { value: markExplicitJs(res.value), taggedJs: true }; + } + return { value: parseScalar(val, this).value, taggedJs: true }; + } + if (/^[|>][+-]?\d*$/.test(val)) { + return { value: this.parseBlockScalar(val, parentIndent), taggedJs: false }; + } + if (val === "") { + const next = this.peekContent(); + const isSeq = next && (next.text === "-" || next.text.startsWith("- ")); + if (next && (next.indent > parentIndent || (next.indent === parentIndent && isSeq))) { + return this.parseBlock(next.indent); + } + return { value: null, taggedJs: false }; + } + if (val.startsWith("[") || val.startsWith("{")) { + return parseFlow(this.collectFlow(val), this); + } + return parseScalar(val, this); + } + + private parseMapping(minIndent: number, seed?: { key: string; rawVal: string; lineIndent: number }): { value: Record; taggedJs: boolean } { + const obj: Record = {}; + let anyJs = false; + if (seed) { + if (seed.key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + const res = this.parseValue(seed.rawVal, seed.lineIndent); + if (res.taggedJs) anyJs = true; + obj[seed.key] = res.value; + } + + while (true) { + const next = this.peekContent(); + if (!next || next.indent < minIndent || next.indent !== minIndent) break; + if (next.text === "-" || next.text.startsWith("- ")) break; + const colon = findUnquotedColon(next.text); + if (colon === -1) break; + this.index++; + const key = unquoteKey(next.text.slice(0, colon)); + if (key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + const rawVal = next.text.slice(colon + 1); + const res = this.parseValue(rawVal, next.indent); + if (res.taggedJs) anyJs = true; + obj[key] = res.value; + } + return { value: anyJs ? markJsExpr(obj) : obj, taggedJs: anyJs }; + } + + private parseSequence(seqIndent: number): { value: unknown[]; taggedJs: boolean } { + const arr: unknown[] = []; + let anyJs = false; + while (true) { + const next = this.peekContent(); + if (!next || next.indent !== seqIndent) break; + if (next.text !== "-" && !next.text.startsWith("- ")) break; + const lineIdx = this.index++; + const afterDash = next.text.slice(1).trimStart(); + if (!afterDash) { + const nested = this.peekContent(); + if (nested && nested.indent > seqIndent) { + const res = this.parseBlock(nested.indent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else { + arr.push(null); + } + continue; + } + + const dashCol = countIndent(this.lines[lineIdx]); + const itemIndent = dashCol + (next.text.length - afterDash.length); + const colon = findUnquotedColon(afterDash); + if (colon !== -1 && !afterDash.startsWith("{") && !afterDash.startsWith("[")) { + const key = unquoteKey(afterDash.slice(0, colon)); + const rawVal = afterDash.slice(colon + 1); + const res = this.parseMapping(itemIndent, { key, rawVal, lineIndent: itemIndent }); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else if (afterDash === "-" || afterDash.startsWith("- ")) { + // Nested inline sequence `- - a` + this.lines[lineIdx] = " ".repeat(itemIndent) + afterDash; + this.index = lineIdx; + const res = this.parseSequence(itemIndent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else { + const res = this.parseValue(afterDash, itemIndent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } + } + return { value: anyJs ? markJsExpr(arr) : arr, taggedJs: anyJs }; + } + + parseTopLevel(): { value: unknown; taggedJs: boolean } { + let next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + if (next.text === "---") { + this.index++; + next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + } + if (next.text === "...") { + this.index++; + if (this.peekContent() !== null) { + throw new Error("Multiple YAML documents are not supported in cordis.patch.yml."); + } + return { value: [], taggedJs: false }; + } + const parsed = this.parseBlock(); + const trailing = this.peekContent(); + if (trailing?.text === "...") { + this.index++; + if (this.peekContent() !== null) { + throw new Error("Incomplete or unsupported YAML in cordis.patch.yml."); + } + } else if (trailing !== null) { + throw new Error("Incomplete or unsupported YAML in cordis.patch.yml."); + } + if (!Array.isArray(parsed.value)) { + throw new Error("Expected a top-level YAML list in cordis.patch.yml."); + } + return parsed; + } + + parseBlock(expectedIndent?: number): { value: unknown; taggedJs: boolean } { + const next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + const indent = expectedIndent ?? next.indent; + if (next.text === "---") { + this.index++; + return this.parseBlock(); + } + if (next.text === "-" || next.text.startsWith("- ")) { + return this.parseSequence(indent); + } + if (next.text.startsWith("[") || next.text.startsWith("{")) { + this.index++; + return parseFlow(this.collectFlow(next.text), this); + } + if (findUnquotedColon(next.text) !== -1) { + return this.parseMapping(indent); + } + this.index++; + return parseScalar(next.text, this); + } +} + +export function parseDshPatchYaml(text: string): { entries: any[]; hasJsExpression: boolean } { + const parser = new YamlParser(text); + const parsed = parser.parseTopLevel(); + return { entries: parsed.value as any[], hasJsExpression: parser.hasJsExpression }; +} + +/** Whether a plain (unquoted) spelling would load back as this exact string. */ +function plainKeepsString(text: string): boolean { + // YAML 1.1 booleans are strings under dsh's core schema; quote them anyway + // so no older reader turns them into booleans. + if (/^(?:y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|<<|=)$/.test(text)) return false; + try { + return resolvePlain(text) === text; + } catch { + return false; + } +} + +function needsQuotes(text: string): boolean { + if (text === "") return true; + if (/^\s|\s$/.test(text)) return true; + if (!plainKeepsString(text)) return true; + if (/^[-?:,\[\]{}#&*!|>'"%@`]/.test(text)) return true; + if (/:(?:\s|$)/.test(text) || /\s#/.test(text)) return true; + return false; +} + +function formatKey(key: string): string { + if (/^[A-Za-z0-9._-]+$/.test(key) && !needsQuotes(key)) return key; + return formatString(key); +} + +const DOUBLE_QUOTED_ESCAPES: Readonly> = { + "\\": "\\\\", + '"': '\\"', + "\0": "\\0", + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\v": "\\v", + "\f": "\\f", + "\r": "\\r", +}; + +function formatString(value: string): string { + // Control and other non-printable characters are only safe escaped. + if (/[\x00-\x1f\x7f-\x9f\u2028\u2029\ufeff]/.test(value)) { + return `"${value.replace( + /[\x00-\x1f\x7f-\x9f"\\\u2028\u2029\ufeff]/g, + (ch) => DOUBLE_QUOTED_ESCAPES[ch] ?? `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`, + )}"`; + } + if (!needsQuotes(value)) return value; + return `'${value.replace(/'/g, "''")}'`; +} + +function formatScalar(value: unknown): string { + if (value === null || value === undefined) return "null"; + if (typeof value === "boolean") return String(value); + if (typeof value === "number") { + if (Number.isNaN(value)) return ".nan"; + if (value === Infinity) return ".inf"; + if (value === -Infinity) return "-.inf"; + if (Object.is(value, -0)) return "-0.0"; + return String(value); + } + return formatString(String(value)); +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function dumpValue(value: unknown, indent: number): string[] { + const pad = " ".repeat(indent); + if (Array.isArray(value)) { + if (value.length === 0) return [`${pad}[]`]; + const lines: string[] = []; + for (const item of value) { + if (isPlainObject(item)) { + const entries = Object.entries(item); + if (entries.length === 0) { + lines.push(`${pad}- {}`); + continue; + } + const [firstKey, firstVal] = entries[0]; + if ((isPlainObject(firstVal) && Object.keys(firstVal).length > 0) || (Array.isArray(firstVal) && firstVal.length > 0)) { + lines.push(`${pad}- ${formatKey(firstKey)}:`); + lines.push(...dumpValue(firstVal, indent + 4)); + } else { + lines.push(`${pad}- ${formatKey(firstKey)}: ${formatInlineEmptyOrScalar(firstVal)}`); + } + for (const [k, v] of entries.slice(1)) { + lines.push(...dumpEntry(k, v, indent + 2)); + } + } else if (Array.isArray(item)) { + if (item.length === 0) lines.push(`${pad}- []`); + else { + lines.push(`${pad}-`); + lines.push(...dumpValue(item, indent + 2)); + } + } else { + lines.push(`${pad}- ${formatScalar(item)}`); + } + } + return lines; + } + if (isPlainObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return [`${pad}{}`]; + const lines: string[] = []; + for (const [k, v] of entries) { + lines.push(...dumpEntry(k, v, indent)); + } + return lines; + } + return [`${pad}${formatScalar(value)}`]; +} + +function formatInlineEmptyOrScalar(value: unknown): string { + if (Array.isArray(value)) return "[]"; + if (isPlainObject(value)) return "{}"; + return formatScalar(value); +} + +function dumpEntry(key: string, value: unknown, indent: number): string[] { + const pad = " ".repeat(indent); + const k = formatKey(key); + if ((isPlainObject(value) && Object.keys(value).length > 0) || (Array.isArray(value) && value.length > 0)) { + return [`${pad}${k}:`, ...dumpValue(value, indent + 2)]; + } + return [`${pad}${k}: ${formatInlineEmptyOrScalar(value)}`]; +} + +export function stringifyDshPatchYaml(entries: unknown[]): string { + if (!Array.isArray(entries) || entries.length === 0) return "[]\n"; + return dumpValue(entries, 0).join("\n") + "\n"; +} diff --git a/runtime/examples.ts b/runtime/examples.ts index 330d4ef..1addef1 100644 --- a/runtime/examples.ts +++ b/runtime/examples.ts @@ -3,6 +3,8 @@ import { join } from "node:path"; import { LocalStore, now } from "./local"; export async function createExampleArtifacts(store: LocalStore): Promise { if (store.state.artifacts.some((a) => a.id === "example-preview")) return; + // Someone deleted the example project: its sample files are not made again. + if (!store.state.projects.some((project) => project.id === "example")) return; const root = join(store.dir, "examples"); await mkdir(root, { recursive: true }); const html = join(root, "workspace-preview.html"); diff --git a/runtime/goal-planner.ts b/runtime/goal-planner.ts index 9f7e800..8101a9a 100644 --- a/runtime/goal-planner.ts +++ b/runtime/goal-planner.ts @@ -5,6 +5,7 @@ import type { Command } from "./commands"; import { approvedHarnessCommand, askInCapsule, + type ReviewAgentOptions, } from "./review-agent"; type Register = ( @@ -24,6 +25,7 @@ export interface GoalPlannerDependencies { relatedFiles: (projectId: string, request: string) => Promise; resolveCommand?: (harness: Harness) => Promise; ask?: typeof askInCapsule; + reviewOptions?: Pick; } const maximumTasks = 5; @@ -125,7 +127,7 @@ export class GoalPlanner { `${readInstruction} for the planning context, then answer with the goal plan as JSON only.`, hooks: {}, }, - { policy: planningPolicy }, + { ...this.deps.reviewOptions, policy: planningPolicy }, ); return { ...readGoalPlan(answer.text, input.request), diff --git a/runtime/local.ts b/runtime/local.ts index 54d641c..ee40215 100644 --- a/runtime/local.ts +++ b/runtime/local.ts @@ -85,12 +85,18 @@ export class LocalStore { initializePlanning(this.state); return this.state; } - save(): Promise { + /** + * Saves the workspace as it is at the moment of the call. `first` runs before + * the file is written: something that must be on disk before the workspace + * that goes with it. + */ + save(first?: () => Promise): Promise { observePlanning(this.state); const serialized = JSON.stringify(this.state, null, 2); const pending = this.writes .catch(() => {}) .then(async () => { + await first?.(); const path = join(this.dir, "workspace.json"); const temp = join(this.dir, "workspace.json.next"); await writeFile(temp, serialized, "utf8"); @@ -100,7 +106,9 @@ export class LocalStore { return pending; } async runtime(): Promise { - const harnesses = await discoverHarnesses(); + const harnesses = await discoverHarnesses(false, undefined, { + dshProfile: this.state.settings.dshProfile, + }); return { appVersion, harnesses, diff --git a/runtime/mac-commands.ts b/runtime/mac-commands.ts index 72aef14..3625ccb 100644 --- a/runtime/mac-commands.ts +++ b/runtime/mac-commands.ts @@ -74,7 +74,9 @@ export async function findMacDesktopApp( ? ["Codex.app", "ChatGPT.app"] : name === "cursor" ? ["Cursor.app"] - : []; + : name === "dsh" + ? ["DeepSeek Harness.app"] + : []; for (const root of appRoots(options)) for (const app of names) { const path = join(root, app); diff --git a/runtime/review-agent.ts b/runtime/review-agent.ts index 1f1ef74..13d5d2e 100644 --- a/runtime/review-agent.ts +++ b/runtime/review-agent.ts @@ -31,6 +31,7 @@ import { probeClaudeCatalog } from "./agents/claude"; import { selectClaudeModel } from "./agents/claude-models"; import { readonlyACPTransport, type StandardHarness } from "./agents/standard-acp"; import { selectStandardACPModel, standardModelMeasurement } from "./agents/acp-models"; +import { inspectDshProfiles } from "./dsh-profiles"; type Json = Record; export interface ReadonlyReviewQuestion { @@ -65,6 +66,12 @@ export interface ReviewAgentOptions { policy?: string; modelPinned?: boolean; localModel?: boolean; + dshProfile?: string; + /** + * Admits a dsh reader process while no setup operation rewrites its + * profile; returns the release to call once the process has exited. + */ + dshAdmission?: () => () => void; commandFor?: typeof findCommand; /** Test transport injection; product callers use the installed approved CLI. */ spawn?: typeof spawn; @@ -735,7 +742,11 @@ async function standardQuestion( harness: StandardHarness, command: Command, capsule: string, prompt: string, requested: string, input: ReadonlyQuestionHooks, options: ReviewAgentOptions, ): Promise { - const transport = await readonlyACPTransport(harness, capsule); + const transport = await readonlyACPTransport( + harness, + capsule, + harness === "dsh" ? options.dshProfile : undefined, + ); const rpc = new ReviewRpc(command, transport.args, capsule, options, true); const source = await readFile(join(capsule, "review-context.json"), "utf8"); let sessionId = "", answer = ""; @@ -1233,8 +1244,30 @@ export async function askInCapsule( : "Read review-context.json"; const prompt = question.prompt(readInstruction); try { - if (harness === "copilot" || harness === "dsh") - return await standardQuestion(harness, command, capsule, prompt, requested, input, { ...options, modelPinned: !!explicit }); + if (harness === "copilot" || harness === "dsh") { + // A dsh reader must not start while setup may be rewriting its profile, + // and setup must not start while it reads; admission covers both. + const release = harness === "dsh" ? options.dshAdmission?.() : undefined; + try { + const dshProfile = + harness === "dsh" + ? options.dshProfile ?? + ( + await inspectDshProfiles(settings?.dshProfile).catch( + () => undefined, + ) + )?.activeProfile ?? + settings?.dshProfile + : undefined; + return await standardQuestion(harness, command, capsule, prompt, requested, input, { + ...options, + modelPinned: !!explicit, + ...(dshProfile !== undefined ? { dshProfile } : {}), + }); + } finally { + release?.(); + } + } return await { codex: codexQuestion, claude: claudeQuestion, diff --git a/runtime/sharing/access.ts b/runtime/sharing/access.ts new file mode 100644 index 0000000..ae84e17 --- /dev/null +++ b/runtime/sharing/access.ts @@ -0,0 +1,200 @@ +import { BetaRequestError, boundedBetaJSON } from "../beta-auth"; +import type { BetaSessionProof } from "../beta"; +import { SharingSignedOut, SharingUnavailable } from "./problems"; + +/** Proof of who is calling, for one call to the sharing service after another. */ +export interface AccessToken { + token: string; + /** The account the sharing service will answer for. */ + accountId: string; +} + +export interface SharingAccessOptions { + /** The Memtrace sign-in, once a rotation in flight has landed. Null: nobody is signed in. */ + session(): Promise; + tokenEndpoint(): URL; + fetcher?: typeof fetch; + now?: () => number; +} + +interface HeldToken extends AccessToken { + sessionId: string; + renewAt: number; +} + +const EXCHANGE_TIMEOUT_MS = 15_000, + RENEW_AHEAD_MS = 60_000, + // The sharing service refuses a token that lives longer than this. + LONGEST_LIFE_SECONDS = 900, + LONGEST_TOKEN = 16384, + LONGEST_ACCOUNT_ID = 200; +const tokenForm = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; + +const unexpectedReply = () => + new SharingUnavailable( + "The sign-in for sharing did not answer with an access token. Try again later.", + ); + +function refusedExchange(status: number): Error { + if (status === 401) + return new SharingSignedOut( + "Your Memtrace sign-in has ended. Sign in again to see the projects you share.", + ); + if (status === 422) + return new SharingUnavailable( + "The name or email on your Memtrace account cannot be used for sharing. Change it at memtrace.io, then try again.", + ); + if (status === 503) + return new SharingUnavailable( + "Sharing is switched off or not set up at memtrace.io right now. Try again later.", + ); + return new SharingUnavailable( + `The sign-in for sharing answered HTTP ${status}. Try again later.`, + ); +} + +/** Who the token says it is for. Its signature is the sharing service's to check. */ +function accountNamedIn(token: string): string { + let account: unknown; + try { + account = JSON.parse( + Buffer.from(token.split(".")[1], "base64url").toString("utf8"), + )?.sub; + } catch { + throw unexpectedReply(); + } + if ( + typeof account !== "string" || + !account || + account.length > LONGEST_ACCOUNT_ID + ) + throw unexpectedReply(); + return account; +} + +function issuedToken( + reply: any, + sentAt: number, + session: BetaSessionProof, +): HeldToken { + const token = reply?.access_token, + lifeSeconds = reply?.expires_in; + if ( + typeof token !== "string" || + token.length > LONGEST_TOKEN || + !tokenForm.test(token) || + reply.token_type !== "Bearer" || + !Number.isInteger(lifeSeconds) || + lifeSeconds <= 0 || + lifeSeconds > LONGEST_LIFE_SECONDS + ) + throw unexpectedReply(); + const accountId = accountNamedIn(token); + if (accountId !== session.accountId) + throw new SharingUnavailable( + "memtrace.io answered for another account than the one signed in here. Sign out and in again.", + ); + const lifeMs = lifeSeconds * 1000; + return { + token, + accountId, + sessionId: session.sessionId, + renewAt: sentAt + lifeMs - Math.min(RENEW_AHEAD_MS, lifeMs / 2), + }; +} + +/** + * Gets an access token for the sharing service from memtrace.io and renews it + * before it expires. The token is kept in memory only. + */ +export class SharingAccess { + private held?: HeldToken; + private exchanging?: Promise; + private readonly fetcher: typeof fetch; + private readonly now: () => number; + constructor(private readonly options: SharingAccessOptions) { + this.fetcher = options.fetcher ?? fetch; + this.now = options.now ?? Date.now; + } + + async current(): Promise { + const session = await this.options.session(); + if (!session) { + this.held = undefined; + throw new SharingSignedOut(); + } + const held = this.held; + if ( + held && + held.sessionId === session.sessionId && + this.now() < held.renewAt + ) + return { token: held.token, accountId: held.accountId }; + const fresh = await (this.exchanging ??= this.exchange(session).finally( + () => (this.exchanging = undefined), + )); + // An exchange already under way may have been for the sign-in before this one. + if (fresh.sessionId !== session.sessionId) return this.current(); + this.held = fresh; + return { token: fresh.token, accountId: fresh.accountId }; + } + + /** Call when the sharing service would not take a token, so the next call asks for another. */ + forget(token: string) { + if (this.held?.token === token) this.held = undefined; + } + + private async exchange(session: BetaSessionProof): Promise { + try { + return await this.request(session); + } catch (problem) { + if (!(problem instanceof SharingSignedOut)) throw problem; + // MemCode's own refresh may have spent that refresh token while the request travelled. + const latest = await this.options.session(); + if (!latest || latest.refreshToken === session.refreshToken) + throw problem; + return this.request(latest); + } + } + + private async request(session: BetaSessionProof): Promise { + const sentAt = this.now(); + const response = await this.send(session); + return issuedToken(await replyOf(response), sentAt, session); + } + + private async send(session: BetaSessionProof): Promise { + try { + // memtrace.io refuses a request that holds anything but these three fields. + return await this.fetcher(this.options.tokenEndpoint(), { + method: "POST", + redirect: "error", + signal: AbortSignal.timeout(EXCHANGE_TIMEOUT_MS), + headers: { + "content-type": "application/json", + accept: "application/json", + }, + body: JSON.stringify({ + refresh_token: session.refreshToken, + device_id: session.deviceId, + session_id: session.sessionId, + }), + }); + } catch { + // The failure may quote the request, so none of it is passed on. + throw new SharingUnavailable( + "memtrace.io could not be reached to sign in to sharing. Check your connection and try again.", + ); + } + } +} + +async function replyOf(response: Response): Promise { + try { + return await boundedBetaJSON(response); + } catch (failure) { + throw failure instanceof BetaRequestError + ? refusedExchange(failure.status) + : unexpectedReply(); + } +} diff --git a/runtime/sharing/addresses.ts b/runtime/sharing/addresses.ts new file mode 100644 index 0000000..499689e --- /dev/null +++ b/runtime/sharing/addresses.ts @@ -0,0 +1,65 @@ +import type { SharingSettings } from "../../src/sharing"; +import { BETA_ORIGIN } from "../beta-auth"; + +/** The two places sharing talks to, checked and ready to use. */ +export interface SharingAddresses { + memsync: URL; + tokenEndpoint: URL; +} + +const thisComputer = ["localhost", "127.0.0.1", "[::1]"]; + +function webAddress(typed: string, what: string): URL { + let address: URL; + try { + address = new URL(typed); + } catch { + throw new Error(`${what} is not a web address. Start it with https://.`); + } + if ( + !["http:", "https:"].includes(address.protocol) || + address.username || + address.password || + address.search || + address.hash + ) + throw new Error( + `${what} must be a plain https:// address, without a sign-in, a question mark or a # part.`, + ); + return address; +} + +const encryptedOrLocal = (address: URL) => + address.protocol === "https:" || thisComputer.includes(address.hostname); + +/** + * Reads where sharing lives from the settings. Null means sharing is not set up. + * Throws a sentence for the person when an address cannot be used. + */ +export function sharingAddresses( + settings: SharingSettings | undefined, +): SharingAddresses | null { + const memsyncUrl = settings?.memsyncUrl.trim() ?? "", + tokenUrl = settings?.tokenUrl.trim() ?? ""; + if (!memsyncUrl && !tokenUrl) return null; + if (!memsyncUrl || !tokenUrl) + throw new Error( + "Sharing needs both addresses: the sharing service and the sign-in address. Enter both, or leave both empty.", + ); + const memsync = webAddress(memsyncUrl, "The sharing service address"); + // Every call carries an access token, and the service itself speaks unencrypted HTTP/2. + if (!encryptedOrLocal(memsync)) + throw new Error( + "The sharing service address must start with https://. Plain http:// works only for a service on this computer.", + ); + const tokenEndpoint = webAddress(tokenUrl, "The sign-in address for sharing"); + // The only sign-in MemCode holds is a memtrace.io one. It is shown to nobody else. + if ( + tokenEndpoint.origin !== BETA_ORIGIN && + !thisComputer.includes(tokenEndpoint.hostname) + ) + throw new Error( + `MemCode shows your Memtrace sign-in only to ${new URL(BETA_ORIGIN).host}. The sign-in address for sharing must be there, or on this computer.`, + ); + return { memsync, tokenEndpoint }; +} diff --git a/runtime/sharing/board/board.ts b/runtime/sharing/board/board.ts new file mode 100644 index 0000000..02c4193 --- /dev/null +++ b/runtime/sharing/board/board.ts @@ -0,0 +1,744 @@ +import type { AppState, Epic, WorkItem } from "../../../src/shared"; +import type { + Cycle, + CustomField, + SavedView, + WorkflowState, +} from "../../../src/planning/types"; +import type { StoryComment } from "../../../src/story-comments"; +import { isActive } from "../../../src/domain"; +import { cycleSnapshot } from "../../../src/planning/history"; +import { + emptyBoard, + type Board, + type Collection, + type Entry, + type Json, +} from "./document"; + +/** + * What of a MemCode project is on its shared board, and what a board from the + * document means for the project on this computer. Everything else in the + * workspace stays here: workers, conversations, changes, reviews, paths. + */ + +/** When the log says an entry was made and last changed, and by which account. */ +export interface EntryStamp { + createdAt?: string; + createdBy?: string; + changedAt?: string; +} +export interface ApplyOptions { + /** The moment to date a change with when the log has not dated it. */ + at: string; + stampOf?: (collection: Collection, id: string) => EntryStamp | undefined; + /** The name of a person on the project, by account. */ + nameOf?: (accountId: string) => string | undefined; +} + +const uuidShape = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const SOMEONE = "Someone on this project"; + +/** + * A lane that comes with a project carries the project's id in front, and that id + * differs on every computer. On the board it is written without it. A lane a + * person added has an id of its own and is written as it is. + */ +function laneOnBoard(projectId: string, id: string): string | undefined { + if (id.startsWith(projectId + ":")) return id.slice(projectId.length + 1); + return uuidShape.test(id) ? id : undefined; +} +const laneHere = (projectId: string, id: string) => + uuidShape.test(id) ? id : `${projectId}:${id}`; + +const entry = ( + fields: Record, + texts: Record = {}, + sets: Record> = {}, +): Entry => ({ + fields: Object.fromEntries( + Object.entries(fields).filter(([, value]) => value !== undefined), + ) as Record, + texts, + sets, +}); +const members = (ids: string[] | undefined) => + Object.fromEntries((ids ?? []).map((id) => [id, true])); + +/** A path a second computer can use: inside the project, with forward slashes. */ +const isPortablePath = (path: string) => + path.length > 0 && + path.length <= 1000 && + !path.includes("\\") && + !path.startsWith("/") && + !/^[A-Za-z]:/.test(path) && + !/[\x00-\x1f]/.test(path) && + path.split("/").every((part) => part && part !== "." && part !== ".."); + +function taskOnBoard(task: WorkItem): Entry { + const lane = task.statusId && laneOnBoard(task.projectId, task.statusId); + const scope = (task.scope ?? []) + .map((path) => path.replaceAll("\\", "/").replace(/\/+$/, "")) + .filter(isPortablePath); + return entry( + { + identifier: task.identifier, + title: task.title, + stage: task.stage, + lane: lane || undefined, + priority: task.priority, + kind: task.kind ?? "feature", + goal: task.epicId ?? null, + cycle: task.cycleId ?? null, + parent: task.parentId ?? null, + estimate: task.estimate ?? null, + startDate: task.startDate ?? null, + dueDate: task.dueDate ?? null, + duplicateOf: task.duplicateOf ?? null, + category: task.category, + archived: !!task.archivedAt, + }, + { description: task.description }, + { + label: members(task.labels), + scope: members(scope), + depends: members(task.dependsOn), + related: members(task.relatedIds), + field: { ...task.customFields }, + step: Object.fromEntries( + task.checklist.map((step, order) => [ + step.id, + { text: step.text, done: step.done, order }, + ]), + ), + }, + ); +} + +const goalOnBoard = (goal: Epic): Entry => + entry( + { + identifier: goal.identifier, + title: goal.title, + phase: goal.phase, + color: goal.color, + order: goal.order, + branch: goal.branch, + baseRevision: goal.baseRevision, + baseBranch: goal.baseBranch, + closed: !!goal.closedAt, + }, + { description: goal.description }, + ); + +const cycleOnBoard = (cycle: Cycle): Entry => + entry({ + name: cycle.name, + goal: cycle.goal, + startDate: cycle.startDate, + endDate: cycle.endDate, + timeZone: cycle.timeZone, + state: cycle.state, + capacity: cycle.capacity, + calendar: cycle.calendar, + }); + +const commentOnBoard = (comment: StoryComment): Entry => + entry({ + task: comment.taskId, + parent: comment.parentId ?? null, + text: comment.text, + reference: comment.reference as Json | undefined, + }); + +/** The shared board of one project, as the workspace on this computer has it. */ +export function boardOf(state: AppState, projectId: string): Board { + const board = emptyBoard(); + const tasks = state.tasks.filter( + (task) => task.projectId === projectId && !task.example, + ); + for (const task of tasks) board.tasks[task.id] = taskOnBoard(task); + for (const goal of state.epics) + if (goal.projectId === projectId) board.goals[goal.id] = goalOnBoard(goal); + for (const cycle of state.cycles) + if (cycle.projectId === projectId) + board.cycles[cycle.id] = cycleOnBoard(cycle); + for (const comment of state.storyComments ?? []) + if (comment.taskId in board.tasks && !comment.deletedAt) + board.comments[comment.id] = commentOnBoard(comment); + for (const lane of state.workflowStates) { + const id = lane.projectId === projectId && laneOnBoard(projectId, lane.id); + if (id) + board.lanes[id] = entry({ + name: lane.name, + stage: lane.stage, + color: lane.color, + order: lane.order, + wipLimit: lane.wipLimit ?? null, + }); + } + for (const field of state.customFields) + if (field.projectId === projectId) + board.fields[field.id] = entry({ + name: field.name, + type: field.type, + options: field.options, + }); + for (const view of state.savedViews) + if (view.projectId === projectId) + board.views[view.id] = entry({ + name: view.name, + mode: view.mode, + groupBy: view.groupBy, + sortBy: view.sortBy, + filters: view.filters as unknown as Json, + }); + return board; +} + +// What is read from a board was written by someone else's computer, so every value +// is checked. One that does not pass is left out and the value already here stays. +type Read = (value: Json | undefined) => T | undefined; +const line = + (longest: number): Read => + (value) => + typeof value === "string" && + value.length > 0 && + value.length <= longest && + !/[\x00-\x1f\x7f]/.test(value) + ? value + : undefined; +const wording = + (longest: number) => + (value: unknown): string | undefined => + typeof value === "string" && value.length <= longest ? value : undefined; +const oneOf = + (...choices: T[]): Read => + (value) => + choices.includes(value as T) ? (value as T) : undefined; +const idOrNone: Read = (value) => + value === null + ? null + : typeof value === "string" && value.length > 0 && value.length <= 250 + ? value + : undefined; +const dayOrNone: Read = (value) => + value === null + ? null + : typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) + ? value + : undefined; +const numberWithin = + (least: number, most: number): Read => + (value) => + typeof value === "number" && + Number.isFinite(value) && + value >= least && + value <= most + ? value + : undefined; +const orNone = + (read: Read): Read => + (value) => + value === null ? null : read(value); +const flag: Read = (value) => + typeof value === "boolean" ? value : undefined; +const or = (read: T | undefined, kept: T): T => + read === undefined ? kept : read; +const memberIds = (set: Record | undefined, most: number) => + Object.keys(set ?? {}) + .filter((id) => id.length > 0 && id.length <= 1000) + .slice(0, most); + +const stageRead = oneOf("planned", "working", "review", "done"); + +function stepsFrom(set: Record | undefined) { + const steps: Array<{ + id: string; + text: string; + done: boolean; + order: number; + }> = []; + for (const [id, value] of Object.entries(set ?? {})) { + const step = value as { text?: Json; done?: Json; order?: Json } | null; + const text = wording(20000)(step?.text); + if (!step || typeof step !== "object" || text === undefined) continue; + steps.push({ + id, + text, + done: step.done === true, + order: typeof step.order === "number" ? step.order : steps.length, + }); + } + return steps + .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)) + .slice(0, 500) + .map(({ id, text, done }) => ({ id, text, done })); +} + +function customValues(set: Record | undefined) { + const values: Record = {}; + for (const [id, value] of Object.entries(set ?? {})) + if ( + value === null || + (typeof value === "number" && Number.isFinite(value)) || + wording(20000)(value) !== undefined + ) + values[id] = value as string | number | null; + return Object.keys(values).length ? values : undefined; +} + +const positive: Read = (value) => + Number.isInteger(value) && (value as number) > 0 + ? (value as number) + : undefined; +/** What each part of a comment's reference may be. A part that is not listed makes it no reference. */ +const referenceParts: Record> = { + kind: oneOf("file", "artifact", "changes", "terminal"), + name: line(240), + quote: wording(20000), + path: (value) => + typeof value === "string" && isPortablePath(value) ? value : undefined, + resultId: line(250), + revision: line(200), + line: positive, + endLine: positive, + page: positive, + sheet: line(200), + range: line(100), + selector: line(1000), +}; + +/** What a comment points at, when the board holds exactly what MemCode writes there. */ +function referenceFrom(value: Json | undefined): StoryComment["reference"] { + if (!value || typeof value !== "object" || Array.isArray(value)) + return undefined; + const parts = Object.entries(value); + const usable = parts.every( + ([name, part]) => referenceParts[name]?.(part) !== undefined, + ); + const { kind, name, quote } = value; + if ( + !usable || + kind === undefined || + name === undefined || + quote === undefined + ) + return undefined; + return value as unknown as StoryComment["reference"]; +} + +/** The shared part of a task as the board has it. Nothing when the board has no usable task there. */ +function taskFromBoard( + projectId: string, + shared: Entry, + kept: WorkItem | undefined, +): Partial | undefined { + const { fields, texts, sets } = shared; + const identifier = or(line(240)(fields.identifier), kept?.identifier), + title = or(line(240)(fields.title), kept?.title), + stage = or(stageRead(fields.stage), kept?.stage); + if (!identifier || !title || !stage) return undefined; + const lane = line(250)(fields.lane); + return { + identifier, + title, + stage, + statusId: lane ? laneHere(projectId, lane) : undefined, + description: or(wording(20000)(texts.description), kept?.description ?? ""), + priority: or( + oneOf("high", "medium", "low")(fields.priority), + kept?.priority ?? "medium", + ), + kind: or( + oneOf("feature", "fix", "refactor", "research", "test")(fields.kind), + kept?.kind ?? "feature", + ), + epicId: or(idOrNone(fields.goal), kept?.epicId ?? null), + cycleId: or(idOrNone(fields.cycle), kept?.cycleId ?? null), + parentId: or(idOrNone(fields.parent), kept?.parentId ?? null), + estimate: or( + orNone(numberWithin(0, 10000))(fields.estimate), + kept?.estimate ?? null, + ), + startDate: or(dayOrNone(fields.startDate), kept?.startDate ?? null), + dueDate: or(dayOrNone(fields.dueDate), kept?.dueDate ?? null), + duplicateOf: or(idOrNone(fields.duplicateOf), kept?.duplicateOf ?? null), + category: or(line(200)(fields.category), kept?.category ?? "Work"), + labels: memberIds(sets.label, 30).filter((label) => label.length <= 100), + scope: memberIds(sets.scope, 200).filter(isPortablePath), + dependsOn: memberIds(sets.depends, 200), + relatedIds: memberIds(sets.related, 200), + customFields: customValues(sets.field), + checklist: stepsFrom(sets.step), + }; +} + +function applyTasks( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +) { + const gone = new Set( + Object.keys(before.tasks).filter((id) => !(id in after.tasks)), + ); + // A task with a worker running on this computer is not taken away under it. + state.tasks = state.tasks.filter( + (task) => + task.projectId !== projectId || !gone.has(task.id) || isActive(task), + ); + for (const [id, shared] of Object.entries(after.tasks)) { + if (JSON.stringify(before.tasks[id]) === JSON.stringify(shared)) continue; + const kept = state.tasks.find((task) => task.id === id); + if (kept && kept.projectId !== projectId) continue; + const read = taskFromBoard(projectId, shared, kept); + if (!read) continue; + const stamp = options.stampOf?.("tasks", id); + const archived = or(flag(shared.fields.archived), !!kept?.archivedAt); + const dated = { + updatedAt: stamp?.changedAt ?? options.at, + archivedAt: archived + ? (kept?.archivedAt ?? stamp?.changedAt ?? options.at) + : null, + }; + if (kept) { + Object.assign(kept, read, dated); + continue; + } + const createdAt = stamp?.createdAt ?? options.at; + state.tasks.push({ + id, + projectId, + harness: state.settings.defaultHarness, + assignment: "auto", + // The brief a worker here starts from, as the first message of any task is. + messages: [ + { + id: `brief:${id}`, + role: "user", + text: read.description || read.title!, + at: createdAt, + }, + ], + run: { state: "idle" }, + createdAt, + ...(read as Required< + Pick + > & + Pick), + ...dated, + }); + } +} + +function applyGoals( + state: AppState, + projectId: string, + before: Board, + after: Board, + at: string, +) { + state.epics = state.epics.filter( + (goal) => + goal.projectId !== projectId || + !(goal.id in before.goals) || + goal.id in after.goals, + ); + for (const [id, shared] of Object.entries(after.goals)) { + if (JSON.stringify(before.goals[id]) === JSON.stringify(shared)) continue; + const kept = state.epics.find((goal) => goal.id === id); + if (kept && kept.projectId !== projectId) continue; + const { fields, texts } = shared; + const identifier = or(line(240)(fields.identifier), kept?.identifier), + title = or(line(240)(fields.title), kept?.title); + if (!identifier || !title) continue; + const closed = or(flag(fields.closed), !!kept?.closedAt); + const read: Omit = { + identifier, + title, + description: or( + wording(20000)(texts.description), + kept?.description ?? "", + ), + phase: or( + oneOf("now", "next", "later")(fields.phase), + kept?.phase ?? "next", + ), + color: or( + oneOf("mint", "cyan", "lavender", "amber")(fields.color), + kept?.color ?? "mint", + ), + order: or(numberWithin(-1e9, 1e9)(fields.order), kept?.order ?? 0), + branch: line(240)(fields.branch), + baseRevision: line(64)(fields.baseRevision), + baseBranch: line(240)(fields.baseBranch), + closedAt: closed ? (kept?.closedAt ?? at) : undefined, + }; + if (kept) Object.assign(kept, read); + else state.epics.push({ id, projectId, ...read }); + } +} + +/** A cycle this computer saw start or finish on the board. */ +interface CycleTurn { + cycle: Cycle; + kind: "started" | "finished"; + at: string; +} + +function applyCycles( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +): CycleTurn[] { + const turns: CycleTurn[] = []; + state.cycles = state.cycles.filter( + (cycle) => + cycle.projectId !== projectId || + !(cycle.id in before.cycles) || + cycle.id in after.cycles, + ); + for (const [id, shared] of Object.entries(after.cycles)) { + if (JSON.stringify(before.cycles[id]) === JSON.stringify(shared)) continue; + const kept = state.cycles.find((cycle) => cycle.id === id); + if (kept && kept.projectId !== projectId) continue; + const { fields } = shared; + const name = or(line(240)(fields.name), kept?.name), + startDate = or(dayOrNone(fields.startDate), kept?.startDate), + endDate = or(dayOrNone(fields.endDate), kept?.endDate); + if (!name || !startDate || !endDate) continue; + const stamp = options.stampOf?.("cycles", id); + const changedAt = stamp?.changedAt ?? options.at; + const state_ = or( + oneOf("planned", "active", "completed")(fields.state), + kept?.state ?? "planned", + ); + const read = { + name, + goal: or(wording(20000)(fields.goal), kept?.goal ?? ""), + startDate, + endDate, + timeZone: or(line(100)(fields.timeZone), kept?.timeZone ?? "UTC"), + state: state_, + capacity: or( + orNone(numberWithin(0, 100000))(fields.capacity), + kept?.capacity ?? null, + ), + calendar: or( + oneOf("weekdays", "calendar")(fields.calendar), + kept?.calendar ?? "weekdays", + ), + // A cycle started or finished when the log says its state changed. + startedAt: + state_ === "planned" ? kept?.startedAt : (kept?.startedAt ?? changedAt), + completedAt: + state_ === "completed" ? (kept?.completedAt ?? changedAt) : undefined, + }; + const was = kept?.state; + const cycle: Cycle = kept + ? Object.assign(kept, read) + : { + id, + projectId, + createdAt: stamp?.createdAt ?? options.at, + snapshots: [], + ...read, + }; + if (!kept) state.cycles.push(cycle); + // Only a start or a finish seen here is recorded. A cycle that arrives + // already started has no baseline: what its scope was then is not known here. + if (was === "planned" && state_ !== "planned" && !cycle.baseline) + turns.push({ cycle, kind: "started", at: cycle.startedAt ?? changedAt }); + if (was && was !== "completed" && state_ === "completed") + turns.push({ + cycle, + kind: "finished", + at: cycle.completedAt ?? changedAt, + }); + } + return turns; +} + +/** + * What starting or finishing a cycle here records, for a cycle started or + * finished on another computer: its scope at the start, and its count at the + * end. Taken once the tasks that came with the change are in. + */ +function recordCycleTurns(state: AppState, turns: CycleTurn[]) { + for (const { cycle, kind, at } of turns) + if (kind === "started") + cycle.baseline ??= cycleSnapshot(state, cycle.id, at); + else cycle.snapshots.push(cycleSnapshot(state, cycle.id, at)); +} + +function applyComments( + state: AppState, + before: Board, + after: Board, + options: ApplyOptions, +) { + const comments = (state.storyComments ??= []); + for (const id of Object.keys(before.comments)) { + const kept = comments.find((comment) => comment.id === id); + // A comment that was taken back keeps its place, so replies still have something to answer. + if (kept && !(id in after.comments) && !kept.deletedAt) + kept.deletedAt = + options.stampOf?.("comments", id)?.changedAt ?? options.at; + } + for (const [id, shared] of Object.entries(after.comments)) { + if (JSON.stringify(before.comments[id]) === JSON.stringify(shared)) + continue; + const kept = comments.find((comment) => comment.id === id); + const { fields } = shared; + const taskId = or(line(250)(fields.task), kept?.taskId), + text = or(wording(20000)(fields.text), kept?.text); + if (!taskId || text === undefined) continue; + const stamp = options.stampOf?.("comments", id); + const parentId = or(idOrNone(fields.parent), kept?.parentId ?? null); + const read = { + taskId, + text, + parentId: parentId ?? undefined, + reference: referenceFrom(fields.reference), + updatedAt: stamp?.changedAt ?? options.at, + deletedAt: undefined, + }; + if (kept) { + Object.assign(kept, read); + continue; + } + const account = stamp?.createdBy; + comments.push({ + id, + ...read, + // The log says who sent a comment. What the comment says about itself is not asked. + author: { + id: account ?? "unknown", + name: (account && options.nameOf?.(account)) || SOMEONE, + source: "memtrace", + }, + createdAt: stamp?.createdAt ?? options.at, + }); + } +} + +/** Lanes, custom fields and saved views are small lists that a project holds whole. */ +function applyProjectLists( + state: AppState, + projectId: string, + before: Board, + after: Board, +) { + const changed = (collection: "lanes" | "fields" | "views") => + JSON.stringify(before[collection]) !== JSON.stringify(after[collection]); + if (changed("lanes") && Object.keys(after.lanes).length) { + const lanes: WorkflowState[] = []; + for (const [id, { fields }] of Object.entries(after.lanes)) { + const name = line(200)(fields.name), + stage = stageRead(fields.stage); + if (!name || !stage) continue; + lanes.push({ + id: laneHere(projectId, id), + projectId, + name, + stage, + color: or(line(100)(fields.color), "#98a59d"), + order: or(numberWithin(-1e9, 1e9)(fields.order), lanes.length), + wipLimit: or(orNone(numberWithin(0, 100000))(fields.wipLimit), null), + }); + } + // A lane that is not on the board and cannot be written there stays where it is. + const local = (lane: WorkflowState) => + lane.projectId !== projectId || !laneOnBoard(projectId, lane.id); + state.workflowStates = [...state.workflowStates.filter(local), ...lanes]; + } + if (changed("fields")) { + const fields: CustomField[] = []; + for (const [id, { fields: read }] of Object.entries(after.fields)) { + const name = line(200)(read.name), + type = oneOf("text", "number", "select")(read.type); + if (!name || !type) continue; + const options = Array.isArray(read.options) + ? read.options.filter( + (option): option is string => + typeof option === "string" && option.length <= 200, + ) + : []; + fields.push({ + id, + projectId, + name, + type, + options: options.slice(0, 200), + }); + } + state.customFields = [ + ...state.customFields.filter((field) => field.projectId !== projectId), + ...fields, + ]; + } + if (changed("views")) { + const views: SavedView[] = []; + for (const [id, { fields }] of Object.entries(after.views)) { + const name = line(200)(fields.name), + mode = oneOf("board", "list", "timeline", "calendar")(fields.mode), + groupBy = oneOf( + "status", + "epic", + "priority", + "harness", + "cycle", + "none", + )(fields.groupBy), + sortBy = oneOf( + "priority", + "updated", + "created", + "due", + "estimate", + )(fields.sortBy); + const filters = fields.filters; + if (!name || !mode || !groupBy || !sortBy) continue; + if (!filters || typeof filters !== "object" || Array.isArray(filters)) + continue; + views.push({ + id, + projectId, + name, + mode, + groupBy, + sortBy, + filters: filters as unknown as SavedView["filters"], + }); + } + state.savedViews = [ + ...state.savedViews.filter((view) => view.projectId !== projectId), + ...views, + ]; + } +} + +/** + * Makes the project on this computer follow a board that changed. Only what + * differs between `before` and `after` is touched, and only the shared part of + * a task: its worker, its conversation and its changes are left alone. + */ +export function applyBoard( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +): void { + applyProjectLists(state, projectId, before, after); + applyGoals(state, projectId, before, after, options.at); + const turns = applyCycles(state, projectId, before, after, options); + applyTasks(state, projectId, before, after, options); + applyComments(state, before, after, options); + recordCycleTurns(state, turns); +} diff --git a/runtime/sharing/board/document.ts b/runtime/sharing/board/document.ts new file mode 100644 index 0000000..c09ae99 --- /dev/null +++ b/runtime/sharing/board/document.ts @@ -0,0 +1,289 @@ +import * as Y from "yjs"; + +/** + * A shared board as one Yjs document: docs/shared-board-layout-proposal.md. + * + * Every collection is a map at the top of the document. An entry is a map of + * fields under the id of the thing it describes. This file knows how entries + * are kept and merged, and nothing about what a task or a goal is. + */ +export const collections = [ + "goals", + "cycles", + "tasks", + "comments", + "lanes", + "fields", + "views", +] as const; +export type Collection = (typeof collections)[number]; +export type Json = + string | number | boolean | null | Json[] | { [key: string]: Json }; + +export interface Entry { + /** Plain values. Each is replaced whole, so the last change to one wins. */ + fields: Record; + /** Long text. A change is written as the difference, so edits in different places both stay. */ + texts: Record; + /** Sets, kept as one key per member (`label:urgent`), so two additions both stay. */ + sets: Record>; +} +/** Every entry of every collection that has not been deleted, by id. */ +export type Board = Record>; + +/** The number MemCode writes into a document it lays out, and the highest it will write to. */ +export const LAYOUT = 1; +/** What marks a change this computer made, as opposed to one that came from the log. */ +export const LOCAL = "local"; +/** The sharing service takes no update larger than this. */ +export const LARGEST_UPDATE = 1024 * 1024; +/** + * How much is written as one change before the rest goes into the next. A + * quarter of what the service takes, so that no update comes near the limit. + */ +const ROOM_IN_ONE_CHANGE = 256 * 1024; +/** One value this large would be an update the service refuses. It is not written. */ +const LARGEST_VALUE = LARGEST_UPDATE - 64 * 1024; + +const META = "meta", + LAYOUT_KEY = "layout", + DELETED = "deleted", + MEMBER_OF = ":"; + +export const emptyBoard = (): Board => + Object.fromEntries(collections.map((name) => [name, {}])) as Board; + +const same = (left: unknown, right: unknown) => + left === right || JSON.stringify(left) === JSON.stringify(right); + +/** The layout the document was written in, or nothing for a document nobody has laid out. */ +export function layoutOf(doc: Y.Doc): number | undefined { + const layout = doc.getMap(META).get(LAYOUT_KEY); + return typeof layout === "number" ? layout : undefined; +} + +function readEntry(kept: Y.Map): Entry & { deleted: boolean } { + const entry: Entry = { fields: {}, texts: {}, sets: {} }; + let deleted = false; + kept.forEach((value, key) => { + if (key === DELETED) deleted = value === true; + else if (value instanceof Y.Text) entry.texts[key] = value.toString(); + else if (value instanceof Y.AbstractType) return; + else if (key.includes(MEMBER_OF)) { + const at = key.indexOf(MEMBER_OF); + (entry.sets[key.slice(0, at)] ??= {})[key.slice(at + 1)] = value as Json; + } else entry.fields[key] = value as Json; + }); + return { ...entry, deleted }; +} + +/** What the document holds now. Deleted entries are left out. */ +export function readBoard(doc: Y.Doc): Board { + const board = emptyBoard(); + for (const collection of collections) + doc.getMap(collection).forEach((kept, id) => { + if (!(kept instanceof Y.Map)) return; + const { deleted, ...entry } = readEntry(kept); + if (!deleted) board[collection][id] = entry; + }); + return board; +} + +/** Where two wordings differ: what to take out of the old one and what to put in its place. */ +export function textChange(from: string, to: string) { + let start = 0; + const shortest = Math.min(from.length, to.length); + while (start < shortest && from[start] === to[start]) start++; + let end = 0; + while ( + end < shortest - start && + from[from.length - 1 - end] === to[to.length - 1 - end] + ) + end++; + // Never cut between the two halves of one character. + const isFirstHalf = (text: string, at: number) => + at >= 0 && text.charCodeAt(at) >= 0xd800 && text.charCodeAt(at) <= 0xdbff; + if (isFirstHalf(from, start - 1)) start--; + if (end > 0 && isFirstHalf(from, from.length - end - 1)) end--; + return { + at: start, + remove: from.length - start - end, + insert: to.slice(start, to.length - end), + }; +} + +function writeText(kept: Y.Map, name: string, wording: string) { + const text = kept.get(name); + if (!(text instanceof Y.Text)) + return void kept.set(name, new Y.Text(wording)); + const change = textChange(text.toString(), wording); + if (change.remove) text.delete(change.at, change.remove); + if (change.insert) text.insert(change.at, change.insert); +} + +/** One thing to write, with a number its update will not be larger than. */ +interface Write { + bytes: number; + run(): void; +} +const OVERHEAD = 48; +const bytesOf = (key: string, value: unknown) => + OVERHEAD + + Buffer.byteLength(key) + + Buffer.byteLength(JSON.stringify(value) ?? ""); + +/** The values that differ between two records, and the ones that are gone. */ +function valueWrites( + kept: () => Y.Map, + was: Record, + now: Record, + keyOf: (name: string) => string, +): Write[] { + const writes: Write[] = []; + for (const name of new Set([...Object.keys(was), ...Object.keys(now)])) { + if (same(was[name], now[name])) continue; + const key = keyOf(name); + if (name in now) + writes.push({ + bytes: bytesOf(key, now[name]), + run: () => kept().set(key, now[name]), + }); + else + writes.push({ bytes: bytesOf(key, null), run: () => kept().delete(key) }); + } + return writes; +} + +/** What it takes to make the document's entry say what `after` says. */ +function entryWrites( + held: Y.Map, + id: string, + before: Entry | undefined, + after: Entry, +): Write[] { + // An entry is made once. Putting a second map under an id that is already there + // would replace the first one whole, with every edit anyone made to it. + const kept = () => { + let entry = held.get(id); + if (!(entry instanceof Y.Map)) { + entry = new Y.Map(); + held.set(id, entry); + } + return entry as Y.Map; + }; + const there = held.get(id); + const known = + before ?? + (there instanceof Y.Map + ? readEntry(there) + : { fields: {}, texts: {}, sets: {} }); + const writes: Write[] = [ + { + bytes: bytesOf(id, null), + run: () => { + const entry = kept(); + if (entry.get(DELETED) === true) entry.delete(DELETED); + }, + }, + ...valueWrites(kept, known.fields, after.fields, (name) => name), + ]; + for (const set of new Set([ + ...Object.keys(known.sets), + ...Object.keys(after.sets), + ])) + writes.push( + ...valueWrites( + kept, + known.sets[set] ?? {}, + after.sets[set] ?? {}, + (member) => set + MEMBER_OF + member, + ), + ); + for (const [name, wording] of Object.entries(after.texts)) + if (known.texts[name] !== wording) + writes.push({ + bytes: bytesOf(name, wording), + run: () => writeText(kept(), name, wording), + }); + return writes; +} + +/** + * Writes entries as few changes as will stay small. An entry goes into one + * change whole unless it is too large for that by itself. + * Answers how many values were too large to write at all. + */ +function writeEntries(doc: Y.Doc, entries: Write[][]): number { + let together: Write[] = [], + room = ROOM_IN_ONE_CHANGE, + tooLarge = 0; + const written = () => { + const writes = together; + together = []; + room = ROOM_IN_ONE_CHANGE; + if (!writes.length) return; + doc.transact(() => { + const meta = doc.getMap(META); + if (meta.get(LAYOUT_KEY) === undefined) meta.set(LAYOUT_KEY, LAYOUT); + for (const write of writes) write.run(); + }, LOCAL); + }; + const add = (writes: Write[], bytes: number) => { + if (bytes > room) written(); + together.push(...writes); + room -= bytes; + }; + for (const all of entries) { + const writes = all.filter((write) => write.bytes <= LARGEST_VALUE); + tooLarge += all.length - writes.length; + const bytes = writes.reduce((sum, write) => sum + write.bytes, 0); + if (bytes <= ROOM_IN_ONE_CHANGE) add(writes, bytes); + else for (const write of writes) add([write], write.bytes); + } + written(); + return tooLarge; +} + +/** + * Writes what changed on this computer into the document. `before` is the + * board as this computer last saw it and `after` as it is now: only what + * differs between the two is written, so a change that arrived from someone + * else in the meantime is not undone. + * Answers how many values were too large for the sharing service to take. + */ +export function writeChanges(doc: Y.Doc, before: Board, after: Board): number { + const entries: Write[][] = []; + for (const collection of collections) { + const held = doc.getMap(collection); + const was = before[collection], + now = after[collection]; + for (const id of Object.keys(was)) + if (!(id in now)) + entries.push([ + { + bytes: bytesOf(id, true), + run: () => { + const gone = held.get(id); + // Marked, not removed: an edit made elsewhere at the same moment is kept. + if (gone instanceof Y.Map) gone.set(DELETED, true); + }, + }, + ]); + for (const [id, entry] of Object.entries(now)) + if (!same(was[id], entry)) + entries.push(entryWrites(held, id, was[id], entry)); + } + return writeEntries(doc, entries); +} + +/** Writes one entry as a change of its own, as when a whole board is first written out. */ +export function writeEntryAlone( + doc: Y.Doc, + collection: Collection, + id: string, + entry: Entry, +): number { + return writeEntries(doc, [ + entryWrites(doc.getMap(collection), id, undefined, entry), + ]); +} diff --git a/runtime/sharing/board/identifiers.ts b/runtime/sharing/board/identifiers.ts new file mode 100644 index 0000000..9fd7ff1 --- /dev/null +++ b/runtime/sharing/board/identifiers.ts @@ -0,0 +1,50 @@ +/** + * Two computers that are apart can both make MC-014: nobody numbers tasks for + * them. The log decides which one keeps it. Every computer reads the log in + * the same order, so every computer works out the same answer. + */ + +/** The place in the log of a task that has not reached it. Such a task gives way to every task that has. */ +export const NOT_IN_THE_LOG = Number.MAX_SAFE_INTEGER; + +export interface NumberedTask { + id: string; + identifier: string; + /** The number of the log entry that made the task. */ + arrived: number; +} + +const numbered = /^(.*?)(\d+)$/; +const earlier = (left: NumberedTask, right: NumberedTask) => + left.arrived - right.arrived || (left.id < right.id ? -1 : 1); + +/** + * The tasks that must take a new identifier so that no two share one, with + * what each becomes. Of the tasks that share one, the first to reach the log + * keeps it. The others get the numbers after the highest in use. + */ +export function newIdentifiers(tasks: NumberedTask[]): Map { + const sharing = new Map(); + const highest = new Map(); + for (const task of tasks) { + const parts = numbered.exec(task.identifier); + if (!parts) continue; + const [, letters, digits] = parts; + highest.set(letters, Math.max(highest.get(letters) ?? 0, Number(digits))); + sharing.set(task.identifier, [ + ...(sharing.get(task.identifier) ?? []), + task, + ]); + } + const giveWay = [...sharing.values()] + .flatMap((group) => [...group].sort(earlier).slice(1)) + .sort(earlier); + const renamed = new Map(); + for (const task of giveWay) { + const [, letters, digits] = numbered.exec(task.identifier)!; + const next = highest.get(letters)! + 1; + highest.set(letters, next); + renamed.set(task.id, letters + String(next).padStart(digits.length, "0")); + } + return renamed; +} diff --git a/runtime/sharing/board/store.ts b/runtime/sharing/board/store.ts new file mode 100644 index 0000000..509ea6d --- /dev/null +++ b/runtime/sharing/board/store.ts @@ -0,0 +1,204 @@ +import { createHash } from "node:crypto"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { replaceWorkspace } from "../../persistence"; +import { collections, type Board } from "./document"; +import type { NotApplied } from "./updates"; + +/** A change this computer made that is not in the log yet. */ +export interface UnsentUpdate { + id: string; + payload: Uint8Array; +} +/** A log entry that was not applied. `failed`: it read as an update and could not be applied. */ +export interface LeftOutUpdate { + sequence: number; + id: string; + author: string; + loggedAt: string; + reason: NotApplied | "failed"; +} +/** What one connected project keeps beside the workspace file. */ +export interface KeptBoard { + /** The number of the last log entry dealt with. */ + cursor: number; + /** + * How many times the log has changed the workspace file. The workspace holds + * the same number, which is how a save that was cut off is told apart. + */ + applied: number; + /** Whether the board here and the board in the log have been brought together. */ + joined: boolean; + /** The board as this computer last wrote or took it. Its own changes are told from this. */ + seen: Board; + unsent: UnsentUpdate[]; + leftOut: LeftOutUpdate[]; + /** The number of the log entry that made each task. It decides who keeps an identifier two tasks share. */ + arrived: Record; + /** The document as the log has built it. */ + log: Uint8Array; +} +/** A save. Leaving `log` out says the document is as it was last saved. */ +export type BoardToKeep = Omit & { log?: Uint8Array }; + +const VERSION = 1; +const STATE = "sync.json", + LOG = "log.bin", + NEXT = ".next"; + +const digestOf = (bytes: Uint8Array) => + createHash("sha256").update(bytes).digest("hex"); +const isMissing = (problem: unknown) => + (problem as NodeJS.ErrnoException).code === "ENOENT"; + +interface StateFile { + version: number; + cursor: number; + applied: number; + joined: boolean; + seen: Board; + unsent: Array<{ id: string; payload: string }>; + leftOut: LeftOutUpdate[]; + arrived?: Record; + log: { bytes: number; sha256: string }; +} + +function isStateFile(read: unknown): read is StateFile { + const file = read as StateFile | null; + return ( + !!file && + typeof file === "object" && + file.version === VERSION && + Number.isSafeInteger(file.cursor) && + Number.isSafeInteger(file.applied) && + typeof file.joined === "boolean" && + !!file.seen && + collections.every( + (name) => file.seen[name] && typeof file.seen[name] === "object", + ) && + Array.isArray(file.unsent) && + file.unsent.every( + (update) => + typeof update?.id === "string" && typeof update.payload === "string", + ) && + Array.isArray(file.leftOut) && + typeof file.log?.sha256 === "string" + ); +} + +/** + * Where one connected project's sync state is kept: a folder with the document + * the log has built and everything else in one file. + * + * A save is written beside what is there and then put in its place. When the + * workspace file has to change with it, the workspace is saved between the two + * steps, so after a crash the pair is either both old or both new. + */ +export class BoardStore { + private logDigest = digestOf(new Uint8Array()); + private logBytes = 0; + constructor(private readonly folder: string) {} + + private path(name: string) { + return join(this.folder, name); + } + private async read(name: string): Promise { + try { + const read: unknown = JSON.parse(await readFile(this.path(name), "utf8")); + return isStateFile(read) ? read : undefined; + } catch (problem) { + if (isMissing(problem) || problem instanceof SyntaxError) + return undefined; + throw problem; + } + } + private drop(...names: string[]) { + return Promise.all( + names.map((name) => rm(this.path(name), { force: true })), + ); + } + + /** + * What was kept, or nothing when there is nothing this workspace can use. + * `workspaceAt` is the number the workspace file holds. + */ + async load(workspaceAt: number): Promise { + const waiting = await this.read(STATE + NEXT); + // A save that waited for the workspace counts only if the workspace got there. + if (waiting?.applied === workspaceAt) await this.commit(); + else await this.drop(STATE + NEXT, LOG + NEXT); + const file = await this.read(STATE); + if (!file || file.applied !== workspaceAt) return undefined; + let log: Uint8Array; + try { + log = await readFile(this.path(LOG)); + } catch (problem) { + if (!isMissing(problem)) throw problem; + log = new Uint8Array(); + } + // A document that is not the one that was saved would quietly lose the board. + if (log.length !== file.log.bytes || digestOf(log) !== file.log.sha256) + return undefined; + this.logDigest = file.log.sha256; + this.logBytes = file.log.bytes; + return { + cursor: file.cursor, + applied: file.applied, + joined: file.joined, + seen: file.seen, + unsent: file.unsent.map((update) => ({ + id: update.id, + payload: Buffer.from(update.payload, "base64"), + })), + leftOut: file.leftOut, + arrived: file.arrived ?? {}, + log, + }; + } + + /** Writes a save beside what is kept. It counts once `commit` has put it in place. */ + async prepare(kept: BoardToKeep): Promise { + await mkdir(this.folder, { recursive: true }); + if (kept.log) { + await writeFile(this.path(LOG + NEXT), kept.log); + this.logDigest = digestOf(kept.log); + this.logBytes = kept.log.length; + } else await this.drop(LOG + NEXT); + const file: StateFile = { + version: VERSION, + cursor: kept.cursor, + applied: kept.applied, + joined: kept.joined, + seen: kept.seen, + unsent: kept.unsent.map((update) => ({ + id: update.id, + payload: Buffer.from(update.payload).toString("base64"), + })), + leftOut: kept.leftOut, + arrived: kept.arrived, + log: { bytes: this.logBytes, sha256: this.logDigest }, + }; + await writeFile(this.path(STATE + NEXT), JSON.stringify(file), "utf8"); + } + + /** Puts the prepared save in place: the document first, then the file that describes it. */ + async commit(): Promise { + try { + await replaceWorkspace(this.path(LOG + NEXT), this.path(LOG)); + } catch (problem) { + // No new document: this save left it as it was, or it is already in place. + if (!isMissing(problem)) throw problem; + } + await replaceWorkspace(this.path(STATE + NEXT), this.path(STATE)); + } + + async save(kept: BoardToKeep): Promise { + await this.prepare(kept); + await this.commit(); + } + + /** Forgets everything kept for this project. */ + remove(): Promise { + return rm(this.folder, { recursive: true, force: true }); + } +} diff --git a/runtime/sharing/board/sync.ts b/runtime/sharing/board/sync.ts new file mode 100644 index 0000000..e840e92 --- /dev/null +++ b/runtime/sharing/board/sync.ts @@ -0,0 +1,825 @@ +import * as Y from "yjs"; +import type { AppState } from "../../../src/shared"; +import type { + SharedBoardStatus, + SharedProjectLink, +} from "../../../src/sharing"; +import { refusalSentences } from "../../../src/sharing-refusals"; +import type { + BoardsApi, + LoggedUpdate, + UpdateReceipt, +} from "../memsync/boards-api"; +import type { GrpcStream } from "../memsync/grpc"; +import { + SharingRefused, + SharingSignedOut, + SharingUnavailable, +} from "../problems"; +import { applyBoard, boardOf, type EntryStamp } from "./board"; +import { + collections, + emptyBoard, + LARGEST_UPDATE, + LAYOUT, + layoutOf, + LOCAL, + readBoard, + writeChanges, + writeEntryAlone, + type Board, + type Collection, +} from "./document"; +import { newIdentifiers, NOT_IN_THE_LOG } from "./identifiers"; +import { + BoardStore, + type BoardToKeep, + type KeptBoard, + type LeftOutUpdate, +} from "./store"; +import { + holdsMore, + idOf, + missingFrom, + nextCall, + whyNotApplied, +} from "./updates"; + +export interface BoardSyncOptions { + /** The project on this computer. */ + projectId: string; + /** The shared project whose log holds its board. */ + sharedProjectId: string; + /** Where this board keeps what it needs between runs. */ + folder: string; + state(): AppState; + boards: BoardsApi; + /** + * Saves the workspace as it is at the moment of the call, and writes it only + * after `first` has finished. + */ + saveWorkspace(first: () => Promise): Promise; + /** What the window shows about this board changed. Nothing needs saving. */ + shown(): void; + /** The names of the people on the shared project, by account. */ + people(): Promise>; + /** How long to wait before trying again after failing this many times in a row. */ + waitBeforeRetry?: (failures: number) => number; +} + +type Kept = Omit; +/** `live`: caught up and listening. The window is told `synced`, `sending` or `newer`. */ +type Condition = "starting" | "live" | "offline" | "apart" | "gone" | "stopped"; +/** The documents went back to what was last saved, and the log is read again from there. */ +class StartAgain extends Error {} + +/** What marks a change that came from the log, as opposed to one this computer made. */ +const FROM_LOG = "log"; +const SOMEONE = "Someone on this project"; +const LEFT_OUT_KEPT = 200, + ARRIVALS_HELD = 256; +const WAITS = [1000, 2000, 5000, 15000, 30000, 60000]; +/** A board that is first written out goes in this order, so what a task points at is there before it. */ +const WRITING_ORDER: Collection[] = [ + "lanes", + "fields", + "views", + "cycles", + "goals", + "tasks", + "comments", +]; +const WORK: Collection[] = ["goals", "cycles", "tasks", "comments"]; +const NEWER = + "A newer MemCode laid this board out. Update MemCode to change it from this computer. Until then it is shown here and what you change stays on this computer."; +const CANNOT_SEND = + "Your changes could not be sent to the shared board yet. They are kept on this computer and sent when it works again."; +const CANNOT_SAVE = + "The workspace could not be saved, so changes from the shared board are waiting. Free disk space, and they are taken up again."; + +/** What a problem with the service says to the person, or nothing for a fault of MemCode's own. */ +const sentenceOf = (problem: unknown) => + problem instanceof SharingUnavailable || + problem instanceof SharingRefused || + problem instanceof SharingSignedOut + ? problem.message + : undefined; +const sameBoard = (left: Board, right: Board) => + JSON.stringify(left) === JSON.stringify(right); +const hasWork = (board: Board) => + WORK.some((collection) => Object.keys(board[collection]).length > 0); +/** The entries of one board whose ids another does not hold. */ +function onlyIn(mine: Board, theirs: Board): Board { + const own = emptyBoard(); + for (const collection of collections) + for (const [id, entry] of Object.entries(mine[collection])) + if (!(id in theirs[collection])) own[collection][id] = entry; + return own; +} + +/** + * Keeps the board of one local project and the board in a shared project's log + * the same: docs/shared-board-layout-proposal.md. + * + * Two documents are kept. One holds exactly what the log has built. The other + * holds that and this computer's own changes that are not in the log yet. The + * app goes on showing the workspace file, which follows the second. + * + * Everything that changes them runs in turn, one after the other. + */ +export class BoardSync { + private readonly store: BoardStore; + private kept: Kept = this.nothingKept(0); + private doc = new Y.Doc(); + private logDoc = new Y.Doc(); + private turns: Promise = Promise.resolve(); + private running?: Promise; + private stopped = false; + private mustReopen = false; + private watching?: GrpcStream; + private arrived: LoggedUpdate[] = []; + private taking?: Promise; + private capturing?: Promise; + private sending?: Promise; + /** What the service has said it logged, in this run. */ + private logged = new Set(); + private repairs = new Set(); + /** Entries that read as updates and could not be applied. */ + private unusable = new Set(); + private names = new Map(); + private askedAbout = new Set(); + private stamps = new Map(); + private arriving?: LoggedUpdate; + private condition: Condition = "starting"; + private detail?: string; + /** Why the last call to send did not get through, while something is still waiting. */ + private notSent?: string; + /** The service turned a change down by one of its rules. Asking again changes nothing. */ + private refused?: string; + /** Both boards have work on them, so they stay two. */ + private apart = false; + private tooLarge = 0; + private lastShown = ""; + private pauses = new Set<() => void>(); + + constructor(private readonly options: BoardSyncOptions) { + this.store = new BoardStore(options.folder); + } + + /** Begins reading the log and sending what this computer has. */ + start(): void { + this.running ??= this.run(); + } + + /** Ends sync for now. What is not sent yet stays on disk for the next start. */ + async stop(): Promise { + this.stopped = true; + this.watching?.cancel(); + for (const end of [...this.pauses]) end(); + // Whatever is being written is finished. A call the service has not + // answered is not waited for: what it brings is dropped when it comes. + await this.turns; + this.doc.destroy(); + this.logDoc.destroy(); + } + + /** Forgets what was kept for this board. For after `stop`. */ + forget(): Promise { + return this.store.remove(); + } + + /** + * Looks at the workspace for changes made on this computer and queues them + * for the log. Called after every save of the workspace. + */ + capture(): Promise { + this.capturing ??= this.inTurn(async () => { + this.capturing = undefined; + if (this.stopped || !this.noteOwnChanges()) return; + await this.store.save(this.toKeep(false)); + await this.settle(); + }); + return this.capturing; + } + + /** The name of someone on the shared project, when it is known. */ + nameOf(accountId: string): string | undefined { + return this.names.get(accountId); + } + + /** Asks once who is on the project, for someone not known yet: they may have joined since. */ + async learnName(accountId: string): Promise { + if (this.names.has(accountId) || this.askedAbout.has(accountId)) return; + this.askedAbout.add(accountId); + await this.learn(); + } + + status(): SharedBoardStatus { + const waiting = this.kept.unsent.length; + const leftOut = new Map< + string, + { by: string; on: string; count: number } + >(); + for (const entry of this.kept.leftOut) { + const by = this.names.get(entry.author) ?? SOMEONE, + on = entry.loggedAt.slice(0, 10); + const line = leftOut.get(`${by}\n${on}`) ?? { by, on, count: 0 }; + line.count++; + leftOut.set(`${by}\n${on}`, line); + } + const live = this.condition === "live", + newer = live && this.isNewer(), + sending = live && !newer && waiting > 0, + refused = sending ? this.refused : undefined, + held = sending && !refused ? this.notSent : undefined; + return { + projectId: this.options.projectId, + state: newer + ? "newer" + : this.condition !== "live" + ? this.condition + : refused + ? "stopped" + : held + ? "offline" + : waiting + ? "sending" + : "synced", + detail: newer ? NEWER : (refused ?? held ?? this.detail), + waiting, + leftOut: [...leftOut.values()], + setAside: this.logDoc.store.pendingStructs !== null, + tooLarge: this.tooLarge, + }; + } + + // ── Reading the log ────────────────────────────────────────────────────── + + private async run(): Promise { + this.mustReopen = true; + void this.learn(); + for (let failures = 0; !this.stopped;) { + try { + if (this.mustReopen) await this.inTurn(() => this.open()); + await this.catchUp(); + if (this.stopped) return; + await this.inTurn(async () => { + if (!this.kept.joined) await this.join(); + // What changed on this computer while sync was not running. + else if (this.noteOwnChanges()) + await this.store.save(this.toKeep(false)); + await this.settle(); + }); + failures = 0; + this.say(this.apart ? "apart" : "live"); + await this.watch(); + // A stream that ends is started again, as the service's own notes say. + failures = 1; + } catch (problem) { + if (this.stopped) return; + if (this.isGone(problem)) return; + failures++; + this.failed(problem); + } + await this.pause(this.waitFor(failures)); + } + } + + private async catchUp(): Promise { + for (;;) { + const page = await this.options.boards.readAfter( + this.options.sharedProjectId, + this.kept.cursor, + ); + if (this.stopped || !page.length) return; + await this.inTurn(() => this.take(page)); + } + } + + private watch(): Promise { + const stream = this.options.boards.watchAfter( + this.options.sharedProjectId, + this.kept.cursor, + (update) => this.arrive(update), + ); + this.watching = stream; + return stream.finished.finally(() => { + if (this.watching === stream) this.watching = undefined; + }); + } + + /** Updates from the stream are taken together when several are waiting. */ + private arrive(update: LoggedUpdate): Promise | undefined { + this.arrived.push(update); + this.taking ??= this.inTurn(async () => { + this.taking = undefined; + await this.take(this.arrived.splice(0)); + await this.settle(); + }).catch((problem) => { + // The stream is read again from what was last saved. + this.failed(problem); + this.watching?.cancel(); + }); + return this.arrived.length > ARRIVALS_HELD ? this.taking : undefined; + } + + private async open(): Promise { + this.mustReopen = false; + const at = this.link()?.applied ?? 0; + let read = await this.store.load(at); + try { + this.rebuild(read ?? { ...this.nothingKept(at), log: new Uint8Array() }); + } catch { + // What was kept cannot be used. The log and the workspace are still whole. + read = undefined; + } + if (read) return; + await this.store.remove(); + this.rebuild({ ...this.nothingKept(at), log: new Uint8Array() }); + } + + private nothingKept(applied: number): Kept { + return { + cursor: 0, + applied, + joined: false, + seen: emptyBoard(), + unsent: [], + leftOut: [], + arrived: {}, + }; + } + + private rebuild({ log, ...kept }: KeptBoard): void { + const doc = new Y.Doc(), + logDoc = new Y.Doc(); + if (log.length) { + Y.applyUpdate(logDoc, log, FROM_LOG); + Y.applyUpdate(doc, log, FROM_LOG); + } + for (const update of kept.unsent) { + if (whyNotApplied(update.id, update.payload)) + throw new Error("A change that was waiting to be sent is damaged."); + Y.applyUpdate(doc, update.payload, FROM_LOG); + } + for (const collection of collections) + logDoc + .getMap(collection) + .observeDeep((events) => this.stamp(collection, events)); + this.doc.destroy(); + this.logDoc.destroy(); + this.doc = doc; + this.logDoc = logDoc; + this.kept = kept; + this.stamps.clear(); + this.arrived = []; + } + + /** Notes which entries the log entry being applied made or changed. */ + private stamp(collection: Collection, events: Y.YEvent[]): void { + const from = this.arriving; + if (!from) return; + for (const event of events) { + const made = event.path.length === 0; + const ids = made + ? [...event.changes.keys.keys()] + : [String(event.path[0])]; + for (const id of ids) { + const key = `${collection}/${id}`; + const stamp = this.stamps.get(key) ?? {}; + if (made && event.changes.keys.get(id)?.action === "add") { + stamp.createdAt = from.loggedAt; + stamp.createdBy = from.author; + if (collection === "tasks") this.kept.arrived[id] ??= from.sequence; + } + stamp.changedAt = from.loggedAt; + this.stamps.set(key, stamp); + } + } + } + + /** + * Deals with the next entries of the log: applies the ones that can be + * applied, writes down the ones that cannot, and makes the workspace follow. + */ + private async take(entries: LoggedUpdate[]): Promise { + const next = entries.filter((entry) => entry.sequence > this.kept.cursor); + if (!next.length || this.stopped) return; + await this.learnNames(next); + if (this.stopped) return; + + // From here until the workspace is asked to save, nothing waits. Whatever + // saves the workspace sees it before all of this or after all of it. + this.noteOwnChanges(); + const before = this.kept.joined ? readBoard(this.doc) : undefined; + if (before) this.stamps.clear(); + const logChanged = this.applyAll(next); + // Until the boards are brought together the workspace follows nothing, and + // nothing is kept: the log is read from its start again on the next run, + // which also gives every entry its author and its time. + if (!before) return; + const follows = this.follow(before, next[next.length - 1].loggedAt); + await this.keep(logChanged, follows); + } + + /** Applies entries in order and moves the log position past each. Says whether any applied. */ + private applyAll(entries: LoggedUpdate[]): boolean { + let applied = false; + for (const entry of entries) { + const id = entry.id.toLowerCase(); + const mine = this.kept.unsent.findIndex((update) => update.id === id); + const why = this.unusable.has(id) + ? "failed" + : whyNotApplied(id, entry.payload); + if (why) this.leaveOut(entry, why); + else if (this.apply(entry, mine < 0)) applied = true; + else { + // Applying threw, and may have left a document half changed. Both go + // back to what was last saved and the log is read again from there, + // this entry left out. + this.unusable.add(id); + this.mustReopen = true; + throw new StartAgain(); + } + // The log has it now, damaged or not. A damaged one is sent again as a repair. + if (mine >= 0) this.kept.unsent.splice(mine, 1); + this.logged.delete(id); + this.kept.cursor = entry.sequence; + } + return applied; + } + + private leaveOut(entry: LoggedUpdate, reason: LeftOutUpdate["reason"]): void { + this.kept.leftOut.push({ + sequence: entry.sequence, + id: entry.id.toLowerCase(), + author: entry.author, + loggedAt: entry.loggedAt, + reason, + }); + this.kept.leftOut.splice(0, this.kept.leftOut.length - LEFT_OUT_KEPT); + } + + /** + * Makes the workspace follow what the entries changed on the board. + * `before` is the board as it was before them. Says whether it changed. + */ + private follow(before: Board, at: string): boolean { + const after = readBoard(this.doc); + if (sameBoard(before, after)) return false; + const state = this.options.state(); + applyBoard(state, this.options.projectId, before, after, { + at, + stampOf: (collection, id) => this.stamps.get(`${collection}/${id}`), + nameOf: (account) => this.names.get(account), + }); + // Read-only on a newer layout: `seen` stays, so changes made here are still found later. + if (this.isNewer()) return true; + this.kept.seen = boardOf(state, this.options.projectId); + // A task that came with an identifier one here already has. + if (this.renumber()) this.noteOwnChanges(); + return true; + } + + /** Applies one entry inside a guard. Says whether it applied. */ + private apply(entry: LoggedUpdate, toBoth: boolean): boolean { + this.arriving = entry; + try { + Y.applyUpdate(this.logDoc, entry.payload, FROM_LOG); + // This computer's own update is in the second document since it was made. + if (toBoth) Y.applyUpdate(this.doc, entry.payload, FROM_LOG); + return true; + } catch { + return false; + } finally { + this.arriving = undefined; + } + } + + private async learnNames(entries: LoggedUpdate[]): Promise { + const unknown = entries.filter( + (entry) => + !this.names.has(entry.author) && !this.askedAbout.has(entry.author), + ); + if (!unknown.length) return; + for (const entry of unknown) this.askedAbout.add(entry.author); + await this.learn(); + } + + private async learn(): Promise { + try { + // Someone who has left the project keeps the name they had. + for (const [account, name] of await this.options.people()) + this.names.set(account, name); + } catch { + // A name is a nicety. The board does not wait for one. + } + } + + // ── This computer's own changes ────────────────────────────────────────── + + private isNewer(): boolean { + return (layoutOf(this.doc) ?? 0) > LAYOUT; + } + + /** Writes what changed on this computer into the document. Says whether there was something. */ + private noteOwnChanges(): boolean { + if (!this.kept.joined || this.isNewer()) return false; + const state = this.options.state(); + // A project that is gone from this computer is not a board that was emptied. + if (!state.projects.some((one) => one.id === this.options.projectId)) + return false; + const now = boardOf(state, this.options.projectId); + if (sameBoard(this.kept.seen, now)) return false; + const made = this.recording(() => { + this.tooLarge += writeChanges(this.doc, this.kept.seen, now); + }); + this.kept.seen = now; + return made > 0; + } + + /** Runs changes to the document and queues each update they make. Says how many. */ + private recording(change: () => void): number { + const made: Uint8Array[] = []; + const listen = (update: Uint8Array, origin: unknown) => { + if (origin === LOCAL) made.push(update); + }; + this.doc.on("update", listen); + try { + change(); + } finally { + this.doc.off("update", listen); + } + for (const payload of made) + this.kept.unsent.push({ id: idOf(payload), payload }); + return made.length; + } + + /** + * Makes the board on this computer and the board in the log one board, once. + * Either this computer shares its project, and its board is written to a log + * that has none. Or it joins a project that has a board, and takes that + * board as it is. Two boards with work on them are never made into one. + */ + private async join(): Promise { + const state = this.options.state(), + projectId = this.options.projectId; + // Nothing of this computer's is in the document before this, so it holds what the log holds. + const shared = readBoard(this.doc); + const own = onlyIn(boardOf(state, projectId), shared); + const joining = hasWork(shared); + this.apart = joining && hasWork(own); + if (this.apart) return; + if (!joining && !this.isNewer()) + this.recording(() => { + for (const collection of WRITING_ORDER) + for (const [id, entry] of Object.entries(own[collection])) + this.tooLarge += writeEntryAlone(this.doc, collection, id, entry); + }); + const joined = readBoard(this.doc); + // What was just written is on this computer already. Only the rest is taken. + const written = onlyIn(joined, shared); + applyBoard(state, projectId, written, joined, { + at: new Date().toISOString(), + stampOf: (collection, id) => this.stamps.get(`${collection}/${id}`), + nameOf: (account) => this.names.get(account), + }); + this.stamps.clear(); + this.kept.joined = true; + if (!this.isNewer()) { + this.kept.seen = boardOf(state, projectId); + if (this.renumber()) this.noteOwnChanges(); + } + await this.keep(true, !sameBoard(written, joined)); + } + + /** + * Gives a new identifier to every task of this project that shares one with + * a task that reached the log before it. Says whether anything changed. + */ + private renumber(): boolean { + const tasks = this.options + .state() + .tasks.filter( + (task) => task.projectId === this.options.projectId && !task.example, + ); + const renamed = newIdentifiers( + tasks.map((task) => ({ + id: task.id, + identifier: task.identifier, + arrived: this.kept.arrived[task.id] ?? NOT_IN_THE_LOG, + })), + ); + let changed = false; + for (const task of tasks) { + const identifier = renamed.get(task.id); + if (!identifier) continue; + task.identifier = identifier; + changed = true; + } + return changed; + } + + /** After the log or this computer changed something: repair, send, and tell the window. */ + private async settle(): Promise { + if (this.stopped) return; + if ( + this.kept.joined && + !this.kept.unsent.length && + !this.isNewer() && + holdsMore(this.doc, this.logDoc) + ) + await this.repair(); + this.send(); + this.report(); + } + + /** + * This computer holds something the log does not, and has nothing waiting + * to be sent: an update of its own was damaged on the way into the log. It + * sends what is missing as a new update. + */ + private async repair(): Promise { + const payload = missingFrom(this.logDoc, this.doc); + if (payload.length > LARGEST_UPDATE) return; + const taken = new Set(this.kept.leftOut.map((entry) => entry.id)); + for (let again = 0; again < 8; again++) { + const id = idOf(payload, again); + if (taken.has(id) || this.repairs.has(id)) continue; + this.repairs.add(id); + this.kept.unsent.push({ id, payload }); + return this.store.save(this.toKeep(false)); + } + } + + // ── Sending ────────────────────────────────────────────────────────────── + + private send(): void { + if (this.refused) return; + this.sending ??= this.sendAll().finally(() => { + this.sending = undefined; + }); + } + + private async sendAll(): Promise { + for (let failures = 0; !this.stopped;) { + const call = nextCall( + this.kept.unsent.filter((update) => !this.logged.has(update.id)), + ); + if (!call.length) return; + try { + const receipts = await this.options.boards.append( + this.options.sharedProjectId, + call, + ); + failures = 0; + this.notSent = undefined; + await this.inTurn(() => this.sent(receipts)); + } catch (problem) { + if (this.stopped || this.isGone(problem)) return; + if (problem instanceof SharingRefused) { + // The service will not take it, now or later. Reading goes on. + this.refused = problem.message; + return this.report(); + } + this.notSent = sentenceOf(problem) ?? CANNOT_SEND; + this.report(); + await this.pause(this.waitFor(++failures)); + } + } + } + + private async sent(receipts: UpdateReceipt[]): Promise { + if (this.stopped) return; + let dropped = false; + for (const receipt of receipts) { + const id = receipt.id.toLowerCase(); + this.logged.add(id); + // Logged at a number this computer is already past: it will not come by again. + const at = this.kept.unsent.findIndex((update) => update.id === id); + if (at >= 0 && receipt.sequence <= this.kept.cursor) { + this.kept.unsent.splice(at, 1); + dropped = true; + } + } + if (dropped) await this.store.save(this.toKeep(false)); + this.report(); + } + + // ── Keeping ────────────────────────────────────────────────────────────── + + private toKeep(withLog: boolean): BoardToKeep { + return { + ...this.kept, + unsent: [...this.kept.unsent], + leftOut: [...this.kept.leftOut], + log: withLog ? Y.encodeStateAsUpdate(this.logDoc) : undefined, + }; + } + + /** + * Saves what is kept. When the workspace changed with it, the workspace is + * saved between writing this save and putting it in place, so that after a + * crash the two are either both as before or both as now. + */ + private async keep(log: boolean, workspace: boolean): Promise { + const link = this.link(); + if (!workspace || !link) return this.store.save(this.toKeep(log)); + link.applied = this.kept.applied = this.kept.applied + 1; + const kept = this.toKeep(log); + for (let failures = 1; ; failures++) { + try { + // Not after a wait: the workspace must be saved as it is right now. + await this.options.saveWorkspace(() => this.store.prepare(kept)); + break; + } catch (problem) { + if (this.stopped) return; + console.error("A change from the shared board was not saved:", problem); + this.say("stopped", CANNOT_SAVE); + await this.pause(this.waitFor(failures)); + if (this.stopped) return; + } + } + await this.store.commit(); + if (this.condition === "stopped" && this.detail === CANNOT_SAVE) + this.say("live"); + } + + // ── Small things ───────────────────────────────────────────────────────── + + private link(): SharedProjectLink | undefined { + return this.options + .state() + .sharedProjectLinks?.find( + (link) => + link.projectId === this.options.projectId && + link.sharedProjectId === this.options.sharedProjectId, + ); + } + + private inTurn(job: () => Promise | Result): Promise { + const turn = this.turns.then(job); + this.turns = turn.catch(() => {}); + return turn; + } + + private waitFor(failures: number): number { + return ( + this.options.waitBeforeRetry?.(failures) ?? + WAITS[Math.min(failures, WAITS.length) - 1] + ); + } + + private pause(ms: number): Promise { + if (this.stopped) return Promise.resolve(); + return new Promise((resolve) => { + const end = () => { + clearTimeout(timer); + this.pauses.delete(end); + resolve(); + }; + const timer = setTimeout(end, ms); + this.pauses.add(end); + }); + } + + /** The shared project is not there for this person any more. Sync ends; the board stays here. */ + private isGone(problem: unknown): boolean { + if ( + !(problem instanceof SharingRefused) || + problem.rule !== "no_such_project" + ) + return false; + this.stopped = true; + this.watching?.cancel(); + for (const end of [...this.pauses]) end(); + this.say("gone", refusalSentences.no_such_project); + return true; + } + + private failed(problem: unknown): void { + if (problem instanceof StartAgain) return this.say("starting"); + const said = sentenceOf(problem); + if (said) return this.say("offline", said); + // Not something the service said: start again from what was last saved. + console.error("Board sync failed and starts again:", problem); + this.mustReopen = true; + this.say( + "offline", + "Board sync ran into a problem and is starting again. Nothing on this computer was lost.", + ); + } + + private say(condition: Condition, detail?: string): void { + this.condition = condition; + this.detail = detail; + this.report(); + } + + private report(): void { + const shown = JSON.stringify(this.status()); + if (shown === this.lastShown) return; + this.lastShown = shown; + this.options.shown(); + } +} diff --git a/runtime/sharing/board/updates.ts b/runtime/sharing/board/updates.ts new file mode 100644 index 0000000..6188744 --- /dev/null +++ b/runtime/sharing/board/updates.ts @@ -0,0 +1,120 @@ +import { createHash } from "node:crypto"; +import * as Y from "yjs"; +import { LARGEST_UPDATE } from "./document"; + +/** + * Updates on their way to and from a board's log: the id each is sent under, + * whether one that arrived may be applied, and what a document holds that the + * log does not. + */ + +/** How many ids the same bytes can be sent under. More than one, so a repair can be told from what it repairs. */ +const IDS_PER_UPDATE = 8; +/** The service takes a hundred updates a call, and four mebibytes unless it is set up otherwise. */ +const MOST_UPDATES_IN_A_CALL = 100, + MOST_BYTES_IN_A_CALL = 3 * 1024 * 1024; + +/** + * The id an update is sent under: a UUID made from its bytes. A reader that + * finds bytes which do not give their id knows they changed after they were + * written. `again` gives the same bytes another id, for sending them a second + * time when the log's copy of the first is damaged. + */ +export function idOf(payload: Uint8Array, again = 0): string { + const hash = createHash("sha256").update(payload); + if (again) hash.update(Uint8Array.of(again)); + const bytes = hash.digest().subarray(0, 16); + // Version 8 is the one for ids made by a rule of the sender's own. + bytes[6] = (bytes[6] & 0x0f) | 0x80; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = bytes.toString("hex"); + return [ + hex.slice(0, 8), + hex.slice(8, 12), + hex.slice(12, 16), + hex.slice(16, 20), + hex.slice(20), + ].join("-"); +} + +export function isMadeFrom(id: string, payload: Uint8Array): boolean { + const sent = id.toLowerCase(); + for (let again = 0; again < IDS_PER_UPDATE; again++) + if (idOf(payload, again) === sent) return true; + return false; +} + +export type NotApplied = "too-large" | "changed" | "unreadable"; + +/** + * Why an update from the log must not be applied, or nothing when it may be. + * Reading it first matters: applying an update that does not read can leave + * the document half changed. + */ +export function whyNotApplied( + id: string, + payload: Uint8Array, +): NotApplied | undefined { + if (payload.length > LARGEST_UPDATE) return "too-large"; + if (!isMadeFrom(id, payload)) return "changed"; + try { + Y.decodeUpdate(payload); + } catch { + return "unreadable"; + } + return undefined; +} + +type Deleted = Array<{ clock: number; len: number }>; +/** Whether every deleted stretch of one list lies inside the stretches of the other. */ +function covers(theirs: Deleted | undefined, mine: Deleted): boolean { + let at = 0; + for (const range of mine) { + let clock = range.clock; + const end = range.clock + range.len; + while (clock < end) { + while ( + theirs && + at < theirs.length && + theirs[at].clock + theirs[at].len <= clock + ) + at++; + const cover = theirs?.[at]; + if (!cover || cover.clock > clock) return false; + clock = cover.clock + cover.len; + } + } + return true; +} + +/** Whether a document holds a change or a deletion that another one lacks. */ +export function holdsMore(mine: Y.Doc, theirs: Y.Doc): boolean { + const known = Y.decodeStateVector(Y.encodeStateVector(theirs)); + for (const [client, clock] of Y.decodeStateVector(Y.encodeStateVector(mine))) + if (clock > (known.get(client) ?? 0)) return true; + const deletedThere = Y.createDeleteSetFromStructStore(theirs.store).clients; + for (const [client, deleted] of Y.createDeleteSetFromStructStore(mine.store) + .clients) + if (!covers(deletedThere.get(client), deleted)) return true; + return false; +} + +/** One update with everything `from` holds that `reader` lacks. */ +export const missingFrom = (reader: Y.Doc, from: Y.Doc): Uint8Array => + Y.encodeStateAsUpdate(from, Y.encodeStateVector(reader)); + +/** The updates to send in the next call: from the front, as many as one call may hold. */ +export function nextCall( + waiting: Update[], +): Update[] { + const call: Update[] = []; + let bytes = 0; + for (const update of waiting) { + if (call.length === MOST_UPDATES_IN_A_CALL) break; + if (call.length && bytes + update.payload.length > MOST_BYTES_IN_A_CALL) + break; + call.push(update); + bytes += update.payload.length; + } + return call; +} diff --git a/runtime/sharing/cards/activity.ts b/runtime/sharing/cards/activity.ts new file mode 100644 index 0000000..d932426 --- /dev/null +++ b/runtime/sharing/cards/activity.ts @@ -0,0 +1,1446 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { + AppState, + Artifact, + Message, + WorkItem, +} from "../../../src/shared"; +import type { StoryReviewRun } from "../../../src/code-review"; +import type { + RunSummary, + SessionActor, + SharedSummary, + TeamSession, +} from "../../../src/team-session"; +import type { + WorkerInputRequest, + WorkerInputResponse, +} from "../../../src/worker-input"; +import type { SharedAsk } from "../../../src/sharing"; +import { replaceWorkspace } from "../../persistence"; +import type { CardsApi, LoggedCardEntry } from "../memsync/cards-api"; +import type { CardReaders } from "../memsync/cards-contract"; +import type { GrpcStream } from "../memsync/grpc"; +import { SharingRefused } from "../problems"; +import { isForPeople, LARGEST_SHARED_FILE } from "./files"; +import { idOf, nextCall } from "../board/updates"; +import { summaryOf } from "./summary"; +import { + cardPayloads, + publicMessage, + publicText, + publicValue, + readCardEntry, + readersOf, + sessionIdOf, + type CardEntry, + type CardRecord, + type DeliveryRecord, + type DeliveryState, + type InputRecord, + type SessionPart, + type SharedResultRecord, + type WorkerMessageRecord, + type WritingDevice, +} from "./entries"; +import { + answerStanding, + answerSummary, + inputRecordOf, + messageStanding, + type Host, +} from "./worker-messages"; + +export interface CardActivityOptions { + /** The project on this computer. */ + projectId: string; + /** The shared project whose cards' logs these are. */ + sharedProjectId: string; + /** This computer. Entries it wrote itself are never shown back to it. */ + device: WritingDevice; + /** Where this project keeps what it sent. */ + folder: string; + state(): AppState; + cards: CardsApi; + /** The latest code review report of a task on this computer. */ + reviewOf(taskId: string): Promise; + /** What a task changed here, as its Changes tab shows it, or nothing when it changed nothing. */ + changesOf?(taskId: string): Promise; + /** A file a task's worker saved here, read to share it. Throws a sentence when it may not be shared. */ + savedFileOf?(taskId: string, artifactId: string): Promise; + /** The name of someone on the shared project, when it is known. */ + nameOf(accountId: string): string | undefined; + /** Asks the sharing service for the name of someone not known yet: they may have joined since. */ + learnName?(accountId: string): Promise; + /** What a card shows changed. Nothing needs saving. */ + shown(): void; + /** The account signed in here. Its own other computers may continue its workers. */ + me: string; + /** Continues a worker run here with a follow-up from another computer, as one typed here. */ + deliver?(taskId: string, message: Message): Promise; + /** Answers what a worker run here waits for, as if it was answered here. */ + answer?( + taskId: string, + inputId: string, + response: WorkerInputResponse, + ): Promise; + waitBeforeRetry?: (failures: number) => number; +} + +interface Waiting { + cardId: string; + id: string; + payload: Uint8Array; + readers: CardReaders; +} +/** What was last sent of each run, so only what changed is sent again. */ +interface Sent { + /** The run as everyone on the project sees it. */ + run?: string; + /** The run as its own account sees it. */ + head?: string; + turns: Record; + review?: string; + summary?: string; + /** What the finished run changed, as last shared. */ + changes?: string; + /** When the run's changes were last looked at: its end, then its code review's. */ + changesLookedAt?: string; + inputs?: Record; +} +/** A message from another computer to a worker run here, and what became of it. */ +interface Handled { + taskId: string; + sessionId: string; + state: DeliveryState; + author: string; + device: WritingDevice; + sentAt: string; + text?: string; + answer?: WorkerMessageRecord["answer"]; +} +/** A message written here, shown on its card until the card's log has it. */ +interface Outgoing { + taskId: string; + message: WorkerMessageRecord; +} +/** A file to share from a card. */ +interface SavedFile { + name: string; + mime: string; + kind: SharedResultRecord["kind"]; + bytes: Uint8Array; +} +interface KeptFile { + version: 1; + sent: Record; + /** The version of each file a worker saved here that was shared on its own, by the file's id. */ + sharedFiles?: Record; + /** Readers is missing from what an older MemCode kept: those are sent for their author alone. */ + waiting: Array<{ + cardId: string; + id: string; + payload: string; + readers?: CardReaders; + }>; + /** How far the log of each card with a worker run here has been read for messages. */ + hosted?: Record; + handled?: Record; + outgoing?: Outgoing[]; +} + +/** A run of a worker on another computer, as its log entries tell it. */ +interface RunElsewhere { + /** The account that wrote the run's first entry. Only its entries count. */ + account: string; + device: WritingDevice; + head: Omit; + turns: Map; + review?: StoryReviewRun; + /** One per round of work in the run, by when its worker wrote it. */ + summaries: Map; + updatedAt: string; + sequence: number; + entries: number; +} +/** A shared file, with the account that named it. The window gets the name only. */ +type KnownResult = SharedResultRecord & { + account: string; + sharedAt: string; + sharedHere: boolean; +}; +/** One card's log, read from `cursor` on and watched. */ +interface Reader { + cursor: number; + stream?: GrpcStream; + reading?: Promise; + stopped: boolean; +} +interface LoggedMessage { + record: WorkerMessageRecord; + author: string; + device: WritingDevice; +} +interface Followed extends Reader { + followers: number; + runs: Map; + results: KnownResult[]; + messages: Map; + /** Per message, the latest delivery by each account that wrote one. */ + deliveries: Map>; + /** Per input, the latest of it by each account that wrote one. */ + inputs: Map>; +} + +const WAITS = [1000, 2000, 5000, 15000, 30000, 60000]; +/** How long after a run here ends its card is still read for messages to it. */ +export const CONTINUABLE_FOR_MS = 3 * 24 * 60 * 60 * 1000; +const SOMEONE = "Someone on this project"; +const progressLabels: Record = { + preparing: "Preparing the worker", + joining: "Coordinating with the goal’s other tasks", + starting: "Starting the harness", + responding: "Worker is responding", + reading: "Reading project context", + editing: "Editing project files", + testing: "Running checks", + working: "Working on the task", + waiting: "Waiting for input or a handoff", + waiting_for_user: "Waiting for an answer on the worker's device", + finishing: "Finishing the worker turn", + stopping: "Stopping the worker", +}; +/** + * A file the service turned down, as when the project is full, is not sent again; one + * that could not reach it is, on the next look. + */ +const skipRefused = (problem: unknown) => { + if (problem instanceof SharingRefused) return; + throw problem; +}; +/** Which version of a worker's file this is: it changes when the worker writes the file again. */ +const versionOf = (file: Artifact) => file.revision ?? file.createdAt; +const fingerprint = (value: unknown) => + createHash("sha256") + .update(JSON.stringify(value) ?? "null") + .digest("hex"); +const uuidShape = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** + * The id of a task's card at the sharing service: the task's own id when it is a + * UUID, as MemCode makes them, and a UUID made from it otherwise. The same on + * every computer. + */ +export function cardIdOf(taskId: string): string { + if (uuidShape.test(taskId)) return taskId.toLowerCase(); + const bytes = createHash("sha256") + .update(`memcode-card\n${taskId}`) + .digest() + .subarray(0, 16); + bytes[6] = (bytes[6] & 0x0f) | 0x80; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = bytes.toString("hex"); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +/** A worker run on this computer, as it may be shared. */ +function sessionOf(task: WorkItem, device: WritingDevice): SessionPart { + const run = task.run; + return { + id: sessionIdOf(device.id, task.id, run.startedAt!), + harness: task.harness, + ...(task.route?.model ? { requestedModel: task.route.model } : {}), + ...(run.measurements?.modelId + ? { actualModel: run.measurements.modelId } + : {}), + state: run.state, + startedAt: run.startedAt, + ...(run.finishedAt ? { finishedAt: run.finishedAt } : {}), + ...(run.error ? { error: publicText(run.error).slice(0, 8000) } : {}), + ...(run.activity + ? { + activity: { + phase: run.activity.phase.slice(0, 100), + label: progressLabels[run.activity.phase] ?? "Working on the task", + updatedAt: run.activity.at, + }, + } + : {}), + messages: task.messages + .filter( + (message) => message.role === "user" || message.role === "assistant", + ) + .slice(-10000) + .map(publicMessage), + }; +} + +/** + * The activity of one connected project's cards at the sharing service. + * + * On the computer that runs a worker, every run on a card of this project is + * written to that card's log as it happens: its state, what it is doing, the + * person's and the worker's turns, and its code review. A file someone shares + * from a card is uploaded and named in the log. + * + * On every computer, a card someone opens is read from its log and followed + * while it is open. A run from another computer is shown on the card, read + * only, and only from entries of the account that started it. + */ +export class CardActivity { + private sent: Record = {}; + private waiting: Waiting[] = []; + private loaded?: Promise; + private turns: Promise = Promise.resolve(); + private sending?: Promise; + private capturing?: Promise; + private followed = new Map(); + /** The cards of workers run here, read for messages to them. */ + private hosting = new Map(); + private hosted: Record = {}; + private handled: Record = {}; + private outgoing: Array = []; + private stopped = false; + private pauses = new Set<() => void>(); + /** Runs whose changes are being shared now, so two captures share them once. */ + private sharingChanges = new Set(); + /** The version of each worker's file shared on its own, by the file's id. */ + private sharedFiles: Record = {}; + /** Files being shared now, so two captures share each once. */ + private sharingFiles = new Set(); + + constructor(private readonly options: CardActivityOptions) {} + + // ── This computer's runs ───────────────────────────────────────────────── + + /** + * Looks at this project's tasks for what a run did since it was last written, and + * shares what a run that finished changed and the files its worker made for people. + */ + capture(): Promise { + this.capturing ??= this.captureRuns() + .then(() => this.shareChangesOfFinishedRuns()) + .then(() => this.shareFilesOfFinishedRuns()); + return this.capturing; + } + + private captureRuns(): Promise { + return this.inTurn(async () => { + this.capturing = undefined; + await this.load(); + if (this.stopped) return; + let fresh = 0; + for (const task of this.tasksRunHere()) { + const made = [ + ...(await this.changesOf(task)), + ...this.inputsOf(task), + ...this.deliveriesOf(task), + ]; + for (const record of made) this.queue(cardIdOf(task.id), record); + fresh += made.length; + // A run that starts here takes over an open card from one elsewhere. + const open = this.followed.get(task.id); + if (open && !open.stopped && task.sharedSession) + this.show(task.id, open); + } + this.host(); + if (!fresh) return; + await this.keep(); + this.send(); + }); + } + + /** + * What each run here that finished changed, shared with everyone on the project. + * They are looked at when the run ends and again when its code review settles, for + * changes recorded after the end, and shared when they differ from what was. A run + * that changed nothing, or more than a file may hold, shares nothing. + */ + private async shareChangesOfFinishedRuns(): Promise { + for (const task of this.tasksRunHere()) { + if (this.stopped || task.run.state !== "finished") continue; + const sessionId = sessionIdOf( + this.options.device.id, + task.id, + task.run.startedAt!, + ); + const sent = (this.sent[sessionId] ??= { turns: {} }); + const settledAt = + task.codeReview?.updatedAt ?? task.run.finishedAt ?? task.run.startedAt; + if ( + sent.changesLookedAt === settledAt || + this.sharingChanges.has(sessionId) + ) + continue; + this.sharingChanges.add(sessionId); + try { + const bytes = await this.options.changesOf?.(task.id); + const print = + bytes && fingerprint(Buffer.from(bytes).toString("base64")); + if ( + bytes?.length && + bytes.length <= LARGEST_SHARED_FILE && + print !== sent.changes + ) { + await this.shareResult(task.id, { + name: `${task.identifier}-changes.json`, + mime: "application/json", + kind: "patch", + bytes, + }); + sent.changes = print; + } + sent.changesLookedAt = settledAt; + await this.inTurn(() => this.keep()); + } finally { + this.sharingChanges.delete(sessionId); + } + } + } + + /** + * The documents, images, sheets and slides a worker made, shared with everyone on + * the project once its run finishes, and again when a later round of work changes + * one. Code and data stay here unless someone shares them, and so does a file + * larger than the service keeps. + */ + private async shareFilesOfFinishedRuns(): Promise { + for (const task of this.tasksRunHere()) { + if (task.run.state !== "finished") continue; + for (const file of this.filesForPeople(task)) { + if (this.stopped) return; + await this.shareFileOnce(task, file); + } + } + } + + private filesForPeople(task: WorkItem): Artifact[] { + return this.options + .state() + .artifacts.filter( + (file) => + file.taskId === task.id && + !file.id.startsWith("shared:") && + isForPeople(file.name) && + this.sharedFiles[file.id] !== versionOf(file), + ); + } + + private async shareFileOnce(task: WorkItem, file: Artifact): Promise { + if (this.sharingFiles.has(file.id) || !this.options.savedFileOf) return; + this.sharingFiles.add(file.id); + try { + const saved = await this.options + .savedFileOf(task.id, file.id) + .catch(() => undefined); + if (saved && saved.bytes.length <= LARGEST_SHARED_FILE) + await this.shareResult(task.id, saved).catch(skipRefused); + this.sharedFiles[file.id] = versionOf(file); + await this.inTurn(() => this.keep()); + } finally { + this.sharingFiles.delete(file.id); + } + } + + /** Names a file someone shared from a card in the card's log, once its bytes are kept. */ + async shareResult( + taskId: string, + file: { + name: string; + mime: string; + kind: SharedResultRecord["kind"]; + bytes: Uint8Array; + }, + ): Promise { + await this.load(); + const stored = await this.options.cards.upload( + this.options.sharedProjectId, + file.bytes, + ); + const result: SharedResultRecord = { + id: crypto.randomUUID(), + name: file.name, + mime: file.mime, + sha256: stored.sha256, + size: stored.size, + kind: file.kind, + }; + await this.inTurn(async () => { + this.queue(cardIdOf(taskId), { kind: "result", result }); + await this.keep(); + }); + this.send(); + await this.sending; + return result; + } + + /** Whether something written here has not reached the sharing service yet. */ + get unsent(): number { + return this.waiting.length; + } + + private tasksRunHere(): WorkItem[] { + return this.options + .state() + .tasks.filter( + (task) => + task.projectId === this.options.projectId && + !task.example && + !!task.run.startedAt, + ); + } + + /** + * What a run here did since it was last written: how it stands, for everyone, and + * what was said and why it failed, for its own account (readersOf). + */ + private async changesOf(task: WorkItem): Promise { + const session = sessionOf(task, this.options.device); + const sent = (this.sent[session.id] ??= { turns: {} }); + const { messages, ...head } = session; + const { error, ...run } = head; + const changed = messages.filter( + (message) => sent.turns[message.id] !== fingerprint(message), + ); + const records: CardRecord[] = []; + const runPrint = fingerprint(run); + if (runPrint !== sent.run) { + records.push({ kind: "session", session: { ...run, messages: [] } }); + sent.run = runPrint; + } + const headPrint = fingerprint(head); + const failedSinceSent = !!error && headPrint !== sent.head; + if (changed.length || failedSinceSent) + records.push({ + kind: "session", + session: { ...head, messages: changed }, + }); + sent.head = headPrint; + for (const message of changed) + sent.turns[message.id] = fingerprint(message); + const summary = summaryOf(task, this.projectFolders()); + const summaryPrint = summary && fingerprint(summary); + if (summary && summaryPrint !== sent.summary) { + records.push({ kind: "summary", sessionId: session.id, summary }); + sent.summary = summaryPrint; + } + if (task.codeReview) { + const review = await this.options.reviewOf(task.id).catch(() => null); + const shared = review && publicValue(review); + const reviewPrint = shared && fingerprint(shared); + if (shared && reviewPrint !== sent.review) { + records.push({ kind: "review", sessionId: session.id, review: shared }); + sent.review = reviewPrint!; + } + } + return records; + } + + /** Where this project's code is on this computer, so a summary names files by their path in it. */ + private projectFolders(): string[] { + const path = this.options + .state() + .projects.find((project) => project.id === this.options.projectId)?.path; + return path ? [path] : []; + } + + /** What a run here waits for, when it is new or has changed since it was written. */ + private inputsOf(task: WorkItem): CardRecord[] { + const startedAt = task.run.startedAt!; + const sessionId = sessionIdOf(this.options.device.id, task.id, startedAt); + const written = ((this.sent[sessionId] ??= { turns: {} }).inputs ??= {}); + return (this.options.state().workerInputs ?? []) + .filter( + (input) => input.taskId === task.id && input.createdAt >= startedAt, + ) + .flatMap((input): CardRecord[] => { + const record = inputRecordOf(input, sessionId); + const print = fingerprint(record); + if (written[input.id] === print) return []; + written[input.id] = print; + return [{ kind: "input", input: record }]; + }); + } + + /** What became of follow-ups from other computers that waited for a worker here. */ + private deliveriesOf(task: WorkItem): CardRecord[] { + const records: CardRecord[] = []; + for (const [messageId, handled] of Object.entries(this.handled)) { + if (handled.taskId !== task.id || handled.state !== "queued") continue; + const turn = task.messages.find((message) => message.id === messageId); + const state: DeliveryState | undefined = + !turn || turn.followupState === "cancelled" + ? "declined" + : turn.promptedAt || turn.pickedUpAt + ? "picked-up" + : turn.followupState === "paused" + ? "failed" + : undefined; + if (state) records.push(this.delivery(messageId, handled, state)); + } + return records; + } + + private delivery( + messageId: string, + handled: Handled, + state: DeliveryState, + detail?: string, + ): CardRecord { + handled.state = state; + return { + kind: "delivery", + delivery: { + messageId, + sessionId: handled.sessionId, + state, + at: new Date().toISOString(), + ...(detail ? { detail: publicText(detail).slice(0, 500) } : {}), + }, + }; + } + + private queue(cardId: string, record: CardRecord): string[] { + const ids: string[] = []; + const readers = readersOf(record); + for (const payload of cardPayloads(record, this.options.device)) { + const id = idOf(payload); + this.waiting.push({ cardId, id, payload, readers }); + ids.push(id); + } + return ids; + } + + private send(): void { + if (this.stopped) return; + this.sending ??= this.sendAll().finally(() => { + this.sending = undefined; + }); + } + + private async sendAll(): Promise { + for (let failures = 0; !this.stopped && this.waiting.length;) { + const cardId = this.waiting[0].cardId; + const call = nextCall( + this.waiting.filter((entry) => entry.cardId === cardId), + ); + try { + await this.options.cards.append( + this.options.sharedProjectId, + cardId, + call.map(({ id, payload, readers }) => ({ id, payload, readers })), + ); + failures = 0; + await this.inTurn(() => this.done(call)); + } catch (problem) { + if (this.stopped) return; + if (problem instanceof SharingRefused) { + if (problem.rule === "no_such_project") return; + // The service will not take these, now or later. The rest still goes. + console.error("A card entry was refused:", problem.rule); + await this.inTurn(() => this.done(call)); + continue; + } + await this.pause(this.waitFor(++failures)); + } + } + } + + private async done(sent: Waiting[]): Promise { + const ids = new Set(sent.map((entry) => entry.id)); + this.waiting = this.waiting.filter((entry) => !ids.has(entry.id)); + await this.keep(); + } + + private load(): Promise { + this.loaded ??= (async () => { + try { + const kept = JSON.parse( + await readFile(join(this.options.folder, "cards.json"), "utf8"), + ) as KeptFile; + if (kept.version !== 1) return; + this.sent = kept.sent ?? {}; + this.waiting = (kept.waiting ?? []).map((entry) => ({ + ...entry, + payload: Buffer.from(entry.payload, "base64"), + readers: entry.readers ?? "only-its-author", + })); + this.hosted = kept.hosted ?? {}; + this.handled = kept.handled ?? {}; + this.outgoing = (kept.outgoing ?? []) as typeof this.outgoing; + this.sharedFiles = kept.sharedFiles ?? {}; + } catch { + // Nothing kept yet, or nothing usable: what runs here is written again in full. + } + if (this.waiting.length) this.send(); + const asking = Object.values(this.handled).filter( + (handled) => handled.state === "asking", + ); + const showAll = () => { + for (const taskId of new Set( + Object.values(this.handled).map((handled) => handled.taskId), + )) + this.showAsks(taskId); + }; + showAll(); + if (asking.length) + void this.learnNames(asking.map((handled) => handled.author)).then( + showAll, + ); + })(); + return this.loaded; + } + + private async keep(): Promise { + // Stopped: a send that ends now writes nothing. What still waited is kept from before. + if (this.stopped) return; + // A message written here is kept until it is sent and its card has read it back. + this.outgoing = this.outgoing.filter( + (sent) => + this.waiting.some((entry) => entry.id === sent.waitingId) || + (this.followed.get(sent.taskId)?.stopped === false && + !this.followed.get(sent.taskId)!.messages.has(sent.message.id)), + ); + const kept: KeptFile = { + version: 1, + sent: this.sent, + waiting: this.waiting.map((entry) => ({ + cardId: entry.cardId, + id: entry.id, + payload: Buffer.from(entry.payload).toString("base64"), + readers: entry.readers, + })), + hosted: this.hosted, + handled: this.handled, + outgoing: this.outgoing, + sharedFiles: this.sharedFiles, + }; + await mkdir(this.options.folder, { recursive: true }); + const path = join(this.options.folder, "cards.json"); + await writeFile(path + ".next", JSON.stringify(kept), "utf8"); + await replaceWorkspace(path + ".next", path); + } + + // ── Cards someone opens ────────────────────────────────────────────────── + + /** Reads a card's log and follows it while the card is open. */ + follow(taskId: string): void { + if (this.stopped) return; + const known = this.followed.get(taskId); + if (known && !known.stopped) { + known.followers++; + return; + } + // A card opened again is read again from its start, by a reader of its own. + const card: Followed = { + followers: 1, + cursor: 0, + runs: new Map(), + results: [], + messages: new Map(), + deliveries: new Map(), + inputs: new Map(), + stopped: false, + }; + this.followed.set(taskId, card); + card.reading = this.readLog(taskId, card, (entries) => + this.take(taskId, card, entries), + ); + } + + /** The card was closed. What it showed stays on it until MemCode is closed. */ + unfollow(taskId: string): void { + const card = this.followed.get(taskId); + if (!card || --card.followers > 0) return; + card.stopped = true; + card.stream?.cancel(); + } + + /** Reads a card's log from the reader's cursor on, then watches it, until stopped. */ + private async readLog( + taskId: string, + reader: Reader, + take: (entries: LoggedCardEntry[]) => void, + ): Promise { + const cardId = cardIdOf(taskId); + for (let failures = 0; !reader.stopped && !this.stopped;) { + try { + for (;;) { + const page = await this.options.cards.readAfter( + this.options.sharedProjectId, + cardId, + reader.cursor, + ); + if (reader.stopped || !page.length) break; + take(page); + } + if (reader.stopped) return; + failures = 0; + const stream = this.options.cards.watchAfter( + this.options.sharedProjectId, + cardId, + reader.cursor, + (entry) => take([entry]), + ); + reader.stream = stream; + await stream.finished; + failures = 1; + } catch (problem) { + if (reader.stopped || this.stopped) return; + if ( + problem instanceof SharingRefused && + problem.rule === "no_such_project" + ) + return; + failures++; + } + await this.pause(this.waitFor(failures)); + } + } + + private take(taskId: string, card: Followed, entries: LoggedCardEntry[]) { + let changed = false; + for (const logged of entries) { + if (logged.sequence <= card.cursor) continue; + card.cursor = logged.sequence; + const read = readCardEntry(logged.payload); + if (!read.readable) continue; + changed = this.apply(card, read.entry, logged) || changed; + } + if (!changed) return; + this.show(taskId, card); + // Someone who joined since this computer last looked: named once it has asked. + const unknown = [ + ...[...card.runs.values()].map((run) => run.account), + ...[...card.messages.values()].map((message) => message.author), + ].filter((account) => !this.options.nameOf(account)); + if (unknown.length) + void this.learnNames(unknown).then(() => { + if (!card.stopped) this.show(taskId, card); + }); + } + + private readonly askedNames = new Set(); + /** Asks once for the names of people this computer does not know yet. */ + private async learnNames(accounts: string[]): Promise { + const fresh = [...new Set(accounts)].filter( + (account) => + !this.options.nameOf(account) && !this.askedNames.has(account), + ); + for (const account of fresh) this.askedNames.add(account); + await Promise.all( + fresh.map((account) => this.options.learnName?.(account).catch(() => {})), + ); + } + + /** Takes one entry into what a card shows. Says whether it changed anything. */ + private apply( + card: Followed, + entry: CardEntry, + logged: LoggedCardEntry, + ): boolean { + if (entry.kind === "result") { + if (card.results.some((result) => result.id === entry.result.id)) + return false; + card.results.push({ + ...entry.result, + account: logged.author, + sharedAt: logged.loggedAt, + sharedHere: entry.device.id === this.options.device.id, + }); + return true; + } + if (entry.kind === "message") { + card.messages.set(entry.message.id, { + record: entry.message, + author: logged.author, + device: entry.device, + }); + return true; + } + if (entry.kind === "delivery" || entry.kind === "input") { + const [kept, id, value] = + entry.kind === "delivery" + ? [card.deliveries, entry.delivery.messageId, entry.delivery] + : [card.inputs, entry.input.id, entry.input]; + const byAccount = (kept.get(id) ?? new Map()) as Map< + string, + typeof value + >; + byAccount.set(logged.author, value); + (kept as Map>).set(id, byAccount); + return true; + } + // A run of this computer's own is shown from the task itself. + if (entry.device.id === this.options.device.id) return false; + if (entry.kind === "session") { + const { messages, ...head } = entry.session; + const run = card.runs.get(head.id); + // A run's conversation counts only from the account that started it. + if (run && run.account !== logged.author) return false; + const kept: RunElsewhere = run ?? { + account: logged.author, + device: entry.device, + head, + turns: new Map(), + summaries: new Map(), + updatedAt: logged.loggedAt, + sequence: logged.sequence, + entries: 0, + }; + kept.head = head; + for (const message of messages) kept.turns.set(message.id, message); + kept.updatedAt = logged.loggedAt; + kept.sequence = logged.sequence; + kept.entries++; + card.runs.set(head.id, kept); + return true; + } + const run = card.runs.get(entry.sessionId); + if (!run || run.account !== logged.author) return false; + if (entry.kind === "summary") + run.summaries.set(entry.summary.at, entry.summary); + else run.review = entry.review; + run.updatedAt = logged.loggedAt; + run.entries++; + return true; + } + + /** Puts what a card's log says on the task, for the card's views. */ + private show(taskId: string, card: Followed): void { + const task = this.options + .state() + .tasks.find( + (item) => + item.id === taskId && item.projectId === this.options.projectId, + ); + if (!task) return; + task.sharedResults = card.results.map(({ account, ...result }) => ({ + ...result, + sharedBy: this.options.nameOf(account) ?? SOMEONE, + })); + const latest = this.latestRun(card); + const localStart = task.run.startedAt ?? ""; + const runsHere = ["preparing", "running", "stopping"].includes( + task.run.state, + ); + if ( + !latest || + runsHere || + String(latest.head.startedAt ?? "") < localStart + ) { + delete task.sharedSession; + delete task.sharedFromLog; + delete task.sharedRunIsYours; + delete task.sharedInputs; + } else { + task.sharedSession = this.sessionFor(task.id, latest, card); + task.sharedFromLog = true; + task.sharedRunIsYours = latest.account === this.options.me; + const inputs = this.inputsFor(task.id, latest, card); + if (inputs.length) task.sharedInputs = inputs; + else delete task.sharedInputs; + } + this.options.shown(); + } + + private latestRun(card: Followed): RunElsewhere | undefined { + return [...card.runs.values()] + .sort((left, right) => + String(left.head.startedAt ?? "").localeCompare( + String(right.head.startedAt ?? ""), + ), + ) + .at(-1); + } + + private hostOf(run: RunElsewhere): Host { + return { + name: this.options.nameOf(run.account) ?? SOMEONE, + device: run.device.name, + isYou: run.account === this.options.me, + }; + } + + private actorOf(author: string, device: WritingDevice): SessionActor { + return { + memberId: fingerprint(["owner", author]).slice(0, 32), + name: this.options.nameOf(author) ?? SOMEONE, + deviceId: device.id, + device: device.name, + }; + } + + /** The messages to a run: those in the card's log, and those written here that it has not read back yet. */ + private messagesTo( + taskId: string, + run: RunElsewhere, + card: Followed, + ): Array { + // A worker that takes a follow-up may start a new run: messages to the host's earlier runs count too. + const hosts = new Set( + [...card.runs.values()] + .filter( + (one) => + one.account === run.account && one.device.id === run.device.id, + ) + .map((one) => one.head.id), + ); + const logged = [...card.messages.values()].filter((message) => + hosts.has(message.record.sessionId), + ); + const known = new Set(logged.map((message) => message.record.id)); + const mine = this.outgoing + .filter( + (sent) => + sent.taskId === taskId && + hosts.has(sent.message.sessionId) && + !known.has(sent.message.id), + ) + .map((sent) => ({ + record: sent.message, + author: this.options.me, + device: this.options.device, + sending: this.waiting.some((entry) => entry.id === sent.waitingId), + })); + return [ + ...logged.map((message) => ({ ...message, sending: false })), + ...mine, + ]; + } + + /** A delivery counts only when the account that started the worker wrote it. */ + private deliveryOf(card: Followed, run: RunElsewhere, messageId: string) { + return card.deliveries.get(messageId)?.get(run.account); + } + + /** What the run waits for, from its own account's entries, with where an answer from here stands. */ + private inputsFor( + taskId: string, + run: RunElsewhere, + card: Followed, + ): WorkerInputRequest[] { + const host = this.hostOf(run); + const answers = this.messagesTo(taskId, run, card).filter( + (message) => message.record.answer, + ); + return [...card.inputs.values()].flatMap((byAccount) => { + const input = byAccount.get(run.account); + if ( + !input || + input.sessionId !== run.head.id || + input.status !== "pending" + ) + return []; + const answer = answers + .filter((message) => message.record.answer!.inputId === input.id) + .at(-1); + const { sessionId, answerHere, ...shown } = input; + return [ + { + ...shown, + taskId, + runId: sessionId, + harness: run.head.harness, + elsewhere: answerHere + ? { + line: `Answer this on ${host.isYou ? "your" : `${host.name}'s`} ${host.device}`, + answerable: false, + } + : answer + ? answerStanding( + this.deliveryOf(card, run, answer.record.id), + host, + answer.sending, + ) + : { answerable: true }, + } as WorkerInputRequest, + ]; + }); + } + + private sessionFor( + taskId: string, + run: RunElsewhere, + card: Followed, + ): TeamSession { + const owner = { + // The window is given names, not account ids. + memberId: fingerprint(["owner", run.account]).slice(0, 32), + name: this.options.nameOf(run.account) ?? SOMEONE, + deviceId: run.device.id, + device: run.device.name, + }; + // A person's turn in a run is by whoever started the run, on that computer. + const turns = [...run.turns.values()].map((turn) => + turn.role === "user" ? { ...turn, actor: owner } : turn, + ); + // A follow-up sent from another computer is by whoever sent it, wherever it stands. + const host = this.hostOf(run); + for (const sent of this.messagesTo(taskId, run, card)) { + if (!sent.record.text) continue; + const actor = this.actorOf(sent.author, sent.device); + const delivered = turns.find((turn) => turn.id === sent.record.id); + if (delivered) { + delivered.actor = actor; + continue; + } + turns.push({ + id: sent.record.id, + role: "user", + text: sent.record.text, + at: sent.record.sentAt, + actor, + ...messageStanding( + this.deliveryOf(card, run, sent.record.id), + host, + sent.sending, + ), + }); + } + turns.sort((left, right) => left.at.localeCompare(right.at)); + return { + ...(run.head as Omit), + storyId: taskId, + epoch: 1, + revision: run.entries, + sequence: run.sequence, + owner, + updatedAt: run.updatedAt, + messages: turns, + ...(run.review ? { review: { ...run.review, taskId } } : {}), + summaries: this.summariesOf(card), + } as TeamSession; + } + + /** The summary of every round of work on the card, by whoever ran it, oldest first. */ + private summariesOf(card: Followed): SharedSummary[] { + return [...card.runs.values()] + .flatMap((run) => { + const { name, device } = this.hostOf(run); + return [...run.summaries.values()].map((summary) => ({ + ...summary, + by: name, + device, + })); + }) + .sort((left, right) => left.at.localeCompare(right.at)); + } + + // ── Messages to workers (MemSync ADR-0015) ─────────────────────────────── + + /** Sends a follow-up to the worker an open card shows from another computer. */ + messageWorker(taskId: string, text: string): Promise { + return this.sendToRun(taskId, { text }); + } + + /** Answers what the worker an open card shows from another computer waits for. */ + async answerWorker( + taskId: string, + inputId: string, + response: WorkerInputResponse, + ): Promise { + const input = this.options + .state() + .tasks.find((task) => task.id === taskId) + ?.sharedInputs?.find((one) => one.id === inputId); + if (!input?.elsewhere?.answerable) + throw new Error( + input?.elsewhere?.line ?? + "The worker is no longer waiting for this. Your answer was not sent.", + ); + return this.sendToRun(taskId, { answer: { inputId, response } }); + } + + private async sendToRun( + taskId: string, + body: Pick, + ): Promise { + await this.load(); + const card = this.followed.get(taskId); + const run = card && !card.stopped ? this.latestRun(card) : undefined; + if (!card || !run) + throw new Error( + "The worker this card shows is not known here yet. Open the card again and send it once more.", + ); + if (run.account !== this.options.me) + throw new Error( + `Only ${this.hostOf(run).name} can continue this worker. Leave a comment on the card instead.`, + ); + const message: WorkerMessageRecord = { + id: randomUUID(), + sessionId: run.head.id, + sentAt: new Date().toISOString(), + ...body, + }; + await this.inTurn(async () => { + const [waitingId] = this.queue(cardIdOf(taskId), { + kind: "message", + message, + }); + this.outgoing.push({ taskId, message, waitingId }); + await this.keep(); + }); + this.show(taskId, card); + this.send(); + return message.id; + } + + /** Reads, for messages, the cards of the workers run here that can still be continued. */ + private host(): void { + if (this.stopped) return; + const now = Date.now(); + const asking = new Set( + Object.values(this.handled) + .filter((handled) => handled.state === "asking") + .map((handled) => handled.taskId), + ); + const wanted = new Set( + this.tasksRunHere() + .filter((task) => continuable(task, now) || asking.has(task.id)) + .map((task) => task.id), + ); + for (const [taskId, reader] of this.hosting) + if (!wanted.has(taskId)) { + reader.stopped = true; + reader.stream?.cancel(); + this.hosting.delete(taskId); + } + for (const taskId of wanted) { + if (this.hosting.has(taskId)) continue; + const reader: Reader = { + cursor: this.hosted[taskId] ?? 0, + stopped: false, + }; + this.hosting.set(taskId, reader); + reader.reading = this.readLog(taskId, reader, (entries) => + this.received(taskId, reader, entries), + ); + } + } + + private received( + taskId: string, + reader: Reader, + entries: LoggedCardEntry[], + ): void { + const messages: Array<{ entry: CardEntry; logged: LoggedCardEntry }> = []; + for (const logged of entries) { + if (logged.sequence <= reader.cursor) continue; + reader.cursor = logged.sequence; + const read = readCardEntry(logged.payload); + if ( + read.readable && + read.entry.kind === "message" && + read.entry.device.id !== this.options.device.id + ) + messages.push({ entry: read.entry, logged }); + } + const cursor = reader.cursor; + void this.inTurn(async () => { + if (this.stopped) return; + for (const { entry, logged } of messages) + await this.receive(taskId, entry, logged); + this.hosted[taskId] = Math.max(this.hosted[taskId] ?? 0, cursor); + await this.keep(); + this.send(); + }).catch((problem) => + console.error("A message to a worker was not taken in:", problem), + ); + } + + /** + * A message to a worker run here, from the account that started the worker: + * the same person on another of their computers. It is carried out at once. + * Nobody else continues a worker; a message in another's name is left alone. + */ + private async receive( + taskId: string, + entry: CardEntry, + logged: LoggedCardEntry, + ): Promise { + if (entry.kind !== "message" || this.handled[entry.message.id]) return; + if (logged.author !== this.options.me) return; + const { message } = entry; + const task = this.options + .state() + .tasks.find( + (item) => + item.id === taskId && item.projectId === this.options.projectId, + ); + const startedAt = task?.run.startedAt; + // For the run here now, or an earlier one this computer wrote to this card. Not for another computer's. + if ( + !startedAt || + (message.sessionId !== + sessionIdOf(this.options.device.id, taskId, startedAt) && + !this.sent[message.sessionId]) + ) + return; + const handled: Handled = { + taskId, + sessionId: message.sessionId, + state: "asking", + author: logged.author, + device: entry.device, + sentAt: message.sentAt, + ...(message.text ? { text: message.text } : {}), + ...(message.answer ? { answer: message.answer } : {}), + }; + this.handled[message.id] = handled; + await this.carryOut(message.id, handled); + this.showAsks(taskId); + } + + /** Hands a message to the worker, as if it was typed or answered here. */ + private async carryOut(messageId: string, handled: Handled): Promise { + const cardId = cardIdOf(handled.taskId); + try { + if (handled.answer) { + if (!this.options.answer) + throw new Error( + "This computer cannot answer a worker for someone else.", + ); + await this.options.answer( + handled.taskId, + handled.answer.inputId, + handled.answer.response, + ); + this.queue(cardId, this.delivery(messageId, handled, "picked-up")); + return; + } + if (!this.options.deliver) + throw new Error( + "This computer cannot continue a worker for someone else.", + ); + await this.options.deliver(handled.taskId, { + id: messageId, + role: "user", + text: handled.text!, + at: new Date().toISOString(), + actor: this.actorOf(handled.author, handled.device), + sourceCommandId: messageId, + }); + this.queue(cardId, this.delivery(messageId, handled, "queued")); + } catch (problem) { + this.queue( + cardId, + this.delivery( + messageId, + handled, + "failed", + problem instanceof Error ? problem.message : String(problem), + ), + ); + } + } + + /** The person here allows or declines a message someone else sent to a worker run here. */ + async decide( + taskId: string, + messageId: string, + allow: boolean, + ): Promise { + await this.load(); + await this.inTurn(async () => { + const handled = this.handled[messageId]; + if (!handled || handled.taskId !== taskId || handled.state !== "asking") + throw new Error("This message is no longer waiting for you."); + if (allow) await this.carryOut(messageId, handled); + else + this.queue( + cardIdOf(taskId), + this.delivery(messageId, handled, "declined"), + ); + this.showAsks(taskId); + await this.keep(); + }); + this.send(); + } + + /** Puts the messages that wait for this person's word on their task. */ + private showAsks(taskId: string): void { + const task = this.options + .state() + .tasks.find( + (item) => + item.id === taskId && item.projectId === this.options.projectId, + ); + if (!task) return; + const inputs = this.options.state().workerInputs ?? []; + const asks: SharedAsk[] = Object.entries(this.handled) + .filter( + ([, handled]) => + handled.taskId === taskId && handled.state === "asking", + ) + .map(([id, handled]) => ({ + id, + from: this.options.nameOf(handled.author) ?? SOMEONE, + device: handled.device.name, + kind: handled.answer ? ("answer" as const) : ("message" as const), + text: handled.answer + ? answerSummary( + inputs.find((input) => input.id === handled.answer!.inputId), + handled.answer.response, + ) + : handled.text!, + sentAt: handled.sentAt, + })) + .sort((left, right) => left.sentAt.localeCompare(right.sentAt)); + if (asks.length) task.sharedAsks = asks; + else delete task.sharedAsks; + this.options.shown(); + } + + // ── Small things ───────────────────────────────────────────────────────── + + async stop(): Promise { + this.stopped = true; + for (const reader of [ + ...this.followed.values(), + ...this.hosting.values(), + ]) { + reader.stopped = true; + reader.stream?.cancel(); + } + for (const end of [...this.pauses]) end(); + await this.turns; + } + + private inTurn(job: () => Promise | Result): Promise { + const turn = this.turns.then(job); + this.turns = turn.catch(() => {}); + return turn; + } + + private waitFor(failures: number): number { + return ( + this.options.waitBeforeRetry?.(failures) ?? + WAITS[Math.min(failures, WAITS.length) - 1] + ); + } + + private pause(ms: number): Promise { + if (this.stopped) return Promise.resolve(); + return new Promise((resolve) => { + const end = () => { + clearTimeout(timer); + this.pauses.delete(end); + resolve(); + }; + const timer = setTimeout(end, ms); + this.pauses.add(end); + }); + } +} + +/** A run here still continued by a message: one that runs, or that ended a little while ago. */ +function continuable(task: WorkItem, now: number): boolean { + if (["preparing", "running", "stopping", "blocked"].includes(task.run.state)) + return true; + const ended = Date.parse(task.run.finishedAt ?? task.run.startedAt ?? ""); + return Number.isFinite(ended) && now - ended < CONTINUABLE_FOR_MS; +} diff --git a/runtime/sharing/cards/entries.ts b/runtime/sharing/cards/entries.ts new file mode 100644 index 0000000..6a463f4 --- /dev/null +++ b/runtime/sharing/cards/entries.ts @@ -0,0 +1,395 @@ +import { createHash } from "node:crypto"; +import { z } from "zod"; +import type { Message } from "../../../src/shared"; +import type { StoryReviewRun } from "../../../src/code-review"; +import type { RunSummary } from "../../../src/team-session"; +import { sessionPayload } from "../../team/session-protocol"; +import { LARGEST_UPDATE } from "../board/document"; +import { workerResponseSchema } from "../../worker-input"; +import type { CardReaders } from "../memsync/cards-contract"; + +/** + * What MemCode writes into a card's activity log at the sharing service + * (MemSync ADR-0014). MemSync never reads an entry; this file is the format. + * + * Kinds of entry, each with the computer that wrote it: + * - `session`: one worker run on that computer, as Team Sync shares it: its + * state, what it is doing, its models, and the person's and the worker's + * turns of the conversation. An entry holds the run's latest state and the + * turns that are new or changed since the run's last entry. + * - `review`: the code review report of that run. + * - `summary`: a finished run's last word: what the worker says it did. + * - `result`: a file someone shared from the card, kept at the service by its + * SHA-256. + * - `message`: something for a worker run on another computer, written by the + * computer it is sent from (MemSync ADR-0015): a follow-up, or an answer to + * what the worker waits for. + * - `delivery`: what became of a message, written by the computer running the + * worker. It counts only from the account that started the worker. + * - `input`: a question or an approval the worker waits for, written by the + * computer running it, so the person can answer from another computer. + */ + +export const CARD_FORMAT = "memcode-card", + CARD_VERSION = 1; + +/** One worker run, or the part of it that is new since its last entry. */ +export type SessionPart = z.infer; +/** A file shared from a card. The bytes are kept at the service by `sha256`. */ +export type SharedResultRecord = z.infer; +/** A follow-up for a worker run on another computer, or an answer to what it waits for. */ +export type WorkerMessageRecord = z.infer; +/** What the computer running a worker did with a message. */ +export type DeliveryRecord = z.infer; +export type DeliveryState = DeliveryRecord["state"]; +/** A question or an approval a worker waits for, as other computers see it. */ +export type InputRecord = z.infer; +export type CardRecord = + | { kind: "session"; session: SessionPart } + | { kind: "review"; sessionId: string; review: StoryReviewRun } + | { kind: "summary"; sessionId: string; summary: RunSummary } + | { kind: "result"; result: SharedResultRecord } + | { kind: "message"; message: WorkerMessageRecord } + | { kind: "delivery"; delivery: DeliveryRecord } + | { kind: "input"; input: InputRecord }; +export interface WritingDevice { + id: string; + /** "Mac", "Windows" or "Linux", as Team Sync names a device. Never a host name. */ + name: string; +} +export type CardEntry = CardRecord & { device: WritingDevice }; + +const uuid = z + .string() + .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i); +const device = z + .object({ + id: uuid, + name: z.enum(["Mac", "Windows", "Linux"]), + }) + .strict(); +// The session as Team Sync shares it, without the ids only its relay uses. +const sessionPart = sessionPayload + .omit({ storyId: true, epoch: true, review: true }) + .extend({ id: uuid }) + .strict(); +const reviewShape = sessionPayload.shape.review.unwrap(); +const resultRecord = z + .object({ + id: uuid, + name: z + .string() + .trim() + .min(1) + .max(240) + .refine( + (name) => + !/[\\/:\x00-\x1f]/.test(name) && name !== "." && name !== "..", + "Use a filename, not a local path.", + ), + mime: z + .string() + .regex(/^[\w.+-]+\/[\w.+-]+$/) + .max(100), + sha256: z.string().regex(/^[0-9a-f]{64}$/), + size: z + .number() + .int() + .min(1) + .max(5 * 1024 * 1024), + kind: z.enum(["report", "artifact", "patch"]), + description: z.string().max(2000).optional(), + }) + .strict(); +const moment = z.string().datetime(); +/** The longest summary the shared format holds. */ +export const LONGEST_SUMMARY = 20_000; +const summaryRecord = z + .object({ + text: z.string().trim().min(1).max(LONGEST_SUMMARY), + at: moment, + }) + .strict(); +/** The longest follow-up a card carries; the app's own message box holds as much. */ +export const LONGEST_WORKER_MESSAGE = 20_000; +const messageRecord = z + .object({ + id: uuid, + sessionId: uuid, + sentAt: moment, + text: z.string().trim().min(1).max(LONGEST_WORKER_MESSAGE).optional(), + answer: z + .object({ + inputId: z.string().min(1).max(200), + response: workerResponseSchema, + }) + .strict() + .optional(), + }) + .strict(); +const deliveryRecord = z + .object({ + messageId: uuid, + sessionId: uuid, + /** + * `queued`: the worker takes it when it is ready. `asking`: it waits for the + * worker's person to allow it. `picked-up`: the worker has it. `declined`: + * the worker's person said no. `failed`: it could not reach the worker. + */ + state: z.enum(["queued", "asking", "picked-up", "declined", "failed"]), + at: moment, + detail: z.string().max(500).optional(), + }) + .strict(); +const choice = z + .object({ + id: z.string().min(1).max(1000), + label: z.string().max(500), + description: z.string().max(2000).optional(), + kind: z.enum(["allow-once", "allow-session", "deny", "other"]).optional(), + }) + .strict(); +const inputRecord = z + .object({ + sessionId: uuid, + id: z.string().min(1).max(200), + kind: z.enum(["approval", "question", "plan"]), + title: z.string().max(4000), + description: z.string().max(8000).optional(), + toolName: z.string().max(200).optional(), + details: z.string().max(8000).optional(), + options: z.array(choice).max(40).optional(), + questions: z + .array( + z + .object({ + id: z.string().min(1).max(1000), + question: z.string().max(4000), + options: z.array(choice).max(40), + multiple: z.boolean().optional(), + allowText: z.boolean().optional(), + secret: z.boolean().optional(), + }) + .strict(), + ) + .max(20) + .optional(), + createdAt: moment, + status: z.enum(["pending", "answered", "cancelled"]), + /** It asks for something secret: it is answered on the worker's computer only. */ + answerHere: z.boolean().optional(), + }) + .strict(); +const envelope = { + format: z.literal(CARD_FORMAT), + version: z.literal(CARD_VERSION), + device, +}; +const entryShape = z.discriminatedUnion("kind", [ + z + .object({ ...envelope, kind: z.literal("session"), session: sessionPart }) + .strict(), + z + .object({ + ...envelope, + kind: z.literal("review"), + sessionId: uuid, + review: reviewShape, + }) + .strict(), + z + .object({ + ...envelope, + kind: z.literal("summary"), + sessionId: uuid, + summary: summaryRecord, + }) + .strict(), + z + .object({ ...envelope, kind: z.literal("result"), result: resultRecord }) + .strict(), + z + .object({ ...envelope, kind: z.literal("message"), message: messageRecord }) + .strict(), + z + .object({ + ...envelope, + kind: z.literal("delivery"), + delivery: deliveryRecord, + }) + .strict(), + z + .object({ ...envelope, kind: z.literal("input"), input: inputRecord }) + .strict(), +]); +/** + * Who reads each kind of entry (MemSync ADR-0019). What a worker and its person said, + * why a run failed, and what continues it stay with the person's own account, on any of + * their computers. Everyone on the project sees that a run happens and how it stands, + * its review and the files shared from its card. + */ +export function readersOf(record: CardRecord): CardReaders { + switch (record.kind) { + case "session": + return record.session.messages.length || record.session.error + ? "only-its-author" + : "everyone"; + case "message": + case "delivery": + case "input": + return "only-its-author"; + case "review": + case "summary": + case "result": + return "everyone"; + } +} + +/** A message is a follow-up or an answer, never both and never neither. */ +const sensible = (entry: CardEntry) => + entry.kind !== "message" || !entry.message.text !== !entry.message.answer; + +/** A local path or a credential never leaves this computer in a shared text. */ +export const publicText = (value: string) => + value + .replace(/\bBearer\s+[^\s"']+/gi, "Bearer ") + .replace( + /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, + "", + ) + .replace( + /(?:[A-Za-z]:[\\/]Users[\\/][^\\/\s]+|\/Users\/[^/\s]+|\/home\/[^/\s]+)/g, + "", + ); + +/** The longest turn the shared format holds. Team Sync holds the same. */ +const LONGEST_TURN = 100_000, + CUT = "\n\n[The rest of this turn was too long to share.]"; + +/** A turn of the conversation as it may be shared: no local references, no review notes. */ +export function publicMessage(message: Message): Message { + const { + id, + role, + at, + streamId, + promptedAt, + pickedUpAt, + queuedAt, + queueOrder, + followupState, + } = message; + return Object.fromEntries( + Object.entries({ + id, + role, + at, + text: shortEnough(publicText(message.text)), + streamId, + promptedAt, + pickedUpAt, + queuedAt, + queueOrder, + followupState, + }).filter(([, value]) => value !== undefined), + ) as unknown as Message; +} + +const shortEnough = (text: string) => + text.length <= LONGEST_TURN + ? text + : text.slice(0, LONGEST_TURN - CUT.length) + CUT; + +/** Every string in a value, redacted. For a review report, which holds text in many places. */ +export const publicValue = (value: T): T => + JSON.parse(JSON.stringify(value), (_key, field) => + typeof field === "string" ? publicText(field) : field, + ); + +/** The id of one worker run on one computer: the same for every entry of that run. */ +export function sessionIdOf( + deviceId: string, + taskId: string, + startedAt: string, +): string { + const bytes = createHash("sha256") + .update(["memcode-card-session", deviceId, taskId, startedAt].join("\n")) + .digest() + .subarray(0, 16); + bytes[6] = (bytes[6] & 0x0f) | 0x80; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = bytes.toString("hex"); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +const encoder = new TextEncoder(); +const encode = (entry: CardEntry) => encoder.encode(JSON.stringify(entry)); +/** An entry must fit the service's limit with room to spare. */ +const ROOM_IN_AN_ENTRY = LARGEST_UPDATE - 16 * 1024; + +/** + * The payloads for one record, each small enough for the service. A session + * whose turns do not fit in one entry is written as several, each with the + * run's state. A review that does not fit loses its per-symbol measurements; + * one that still does not fit is not shared, and nothing comes back. + */ +export function cardPayloads( + record: CardRecord, + writer: WritingDevice, +): Uint8Array[] { + const entry = { format: CARD_FORMAT, version: CARD_VERSION, device: writer }; + const whole = encode({ ...entry, ...record } as CardEntry); + if (whole.length <= ROOM_IN_AN_ENTRY) return [whole]; + if (record.kind === "review") { + const lighter = encode({ + ...entry, + ...record, + review: { ...record.review, metrics: [] }, + } as CardEntry); + return lighter.length <= ROOM_IN_AN_ENTRY ? [lighter] : []; + } + if (record.kind !== "session") return []; + const { messages, ...state } = record.session; + const parts: Uint8Array[] = []; + let together: Message[] = []; + const written = (turns: Message[]) => + encode({ + ...entry, + kind: "session", + session: { ...state, messages: turns }, + } as CardEntry); + for (const message of messages) { + if (written([...together, message]).length > ROOM_IN_AN_ENTRY) { + if (together.length) parts.push(written(together)); + together = []; + } + together.push(message); + } + parts.push(written(together)); + return parts; +} + +export type ReadEntry = + { readable: true; entry: CardEntry } | { readable: false; newer: boolean }; + +const decoder = new TextDecoder("utf-8", { fatal: true }); + +/** What an entry from the log says, when it is an entry MemCode can trust the shape of. */ +export function readCardEntry(payload: Uint8Array): ReadEntry { + let value: unknown; + try { + value = JSON.parse(decoder.decode(payload)); + } catch { + return { readable: false, newer: false }; + } + const read = entryShape.safeParse(value); + if (read.success && sensible(read.data as unknown as CardEntry)) + return { readable: true, entry: read.data as unknown as CardEntry }; + const version = (value as { format?: unknown; version?: unknown } | null) + ?.version; + const ours = (value as { format?: unknown } | null)?.format === CARD_FORMAT; + return { + readable: false, + newer: ours && typeof version === "number" && version > CARD_VERSION, + }; +} diff --git a/runtime/sharing/cards/files.ts b/runtime/sharing/cards/files.ts new file mode 100644 index 0000000..d65eabc --- /dev/null +++ b/runtime/sharing/cards/files.ts @@ -0,0 +1,102 @@ +import { realpath, readFile, stat } from "node:fs/promises"; +import { basename, extname } from "node:path"; +import type { AppState, Artifact } from "../../../src/shared"; +import { canonicalArtifactRoots } from "../../files"; +import { within } from "../../local"; + +/** The most a project can share in one file (MemSync ADR-0014). */ +export const LARGEST_SHARED_FILE = 5 * 1024 * 1024; + +// The types Team Sync publishes under, kept here because Team Sync keeps its own private. +const fileTypes: Record = { + ".md": "text/markdown", + ".txt": "text/plain", + ".html": "text/html", + ".htm": "text/html", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", + ".gif": "image/gif", + ".pdf": "application/pdf", + ".json": "application/json", + ".csv": "text/csv", + ".patch": "text/x-diff", + ".diff": "text/x-diff", + ".docx": + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".pptx": + "application/vnd.openxmlformats-officedocument.presentationml.presentation", +}; +export const fileTypeOf = (name: string) => + fileTypes[extname(name).toLowerCase()] ?? "application/octet-stream"; + +// What a worker makes for people to read or look at, not for the code: documents, +// images, sheets and slides. +const madeForPeople = new Set([ + ".md", + ".txt", + ".pdf", + ".html", + ".htm", + ".csv", + ".png", + ".jpg", + ".jpeg", + ".webp", + ".gif", + ".svg", + ".docx", + ".xlsx", + ".pptx", +]); + +/** Whether a file a worker saved is shared with the project on its own when the run finishes. */ +export const isForPeople = (name: string) => + madeForPeople.has(extname(name).toLowerCase()); + +/** How a file from a card is previewed, by its type. */ +export const previewKindOf = (mime: string): Artifact["kind"] => + mime.startsWith("image/") ? "image" : /html/.test(mime) ? "html" : "text"; + +/** + * The bytes of a file a task saved, when it may be shared: only one of the + * task's own saved outputs, at most 5 MB. + */ +export async function shareableFile( + dataDir: string, + state: AppState, + taskId: string, + artifactId: string, +) { + const task = state.tasks.find((item) => item.id === taskId); + const artifact = state.artifacts.find( + (item) => item.id === artifactId && item.taskId === taskId, + ); + if (!task || !artifact) + throw new Error("Choose a file this task saved to share it."); + const path = await realpath(artifact.path); + const roots = await canonicalArtifactRoots(dataDir, task); + if (!roots.some((root) => within(root, path))) + throw new Error("Only files this task saved can be shared."); + const info = await stat(path); + if (!info.isFile()) throw new Error("Only a file can be shared."); + if (!info.size) + throw new Error("That file is empty, so there is nothing in it to share."); + if (info.size > LARGEST_SHARED_FILE) + throw new Error( + "That file is larger than 5 MB, which is the most a project can share in one file.", + ); + const name = basename(artifact.name); + return { + name, + mime: fileTypeOf(name), + kind: + artifact.purpose === "report" + ? ("report" as const) + : ("artifact" as const), + bytes: await readFile(path), + }; +} diff --git a/runtime/sharing/cards/summary.ts b/runtime/sharing/cards/summary.ts new file mode 100644 index 0000000..eb2a147 --- /dev/null +++ b/runtime/sharing/cards/summary.ts @@ -0,0 +1,76 @@ +import type { WorkItem } from "../../../src/shared"; +import type { RunSummary } from "../../../src/team-session"; +import { LONGEST_SUMMARY, publicText } from "./entries"; + +/** + * What the others on a shared project read of a worker's run (MemSync ADR-0019): the + * summary it ends a round of work with, written for people who see neither the + * conversation nor the worker's computer. + */ + +/** The line the brief asks a worker to start its summary for the project with. */ +export const SUMMARY_HEADING = "Summary for the project:"; + +// The heading as workers write it: plain, in bold, as a Markdown heading, or as the +// "Project summary:" an earlier brief led them to. +const HEADING = + /^[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?(?:summary for the project|project summary):?(?:\*\*|__)?:?[ \t]*/gim; +const MARKDOWN_LINK = /\[([^\]\n]+)\]\(([^)\s]+)(?:[ \t]+"[^"\n]*")?\)/g; +const WEB_ADDRESS = /^(?:https?:|mailto:)/i; +// What publicText leaves of a path in a home folder: shown as the file's name. +const PATH_IN_A_HOME = /\/(?:[^\s)\]`'"]*\/)?([^\s/)\]`'"]+)/g; + +/** + * What a finished round of work says it did: the section of the worker's last message + * headed for the project, or the whole message when it has no such section. + */ +export function summaryOf( + task: WorkItem, + projectFolders: string[] = [], +): RunSummary | undefined { + const { state, startedAt, workspace, worktree } = task.run; + if (state !== "finished" || !startedAt) return undefined; + const last = task.messages + .filter( + (message) => message.role === "assistant" && message.at >= startedAt, + ) + .at(-1); + if (!last) return undefined; + const folders = [workspace, worktree, ...projectFolders].filter( + (folder): folder is string => !!folder, + ); + const text = readableSummary(sectionForTheProject(last.text), folders).slice( + 0, + LONGEST_SUMMARY, + ); + return text ? { text, at: last.at } : undefined; +} + +function sectionForTheProject(message: string): string { + const headings = [...message.matchAll(HEADING)]; + const last = headings.at(-1); + return last ? message.slice(last.index + last[0].length) : message; +} + +/** + * A summary as someone on another computer can read it: a link to a file on the + * worker's computer becomes the file's name, a path in the project becomes the path + * in the project, any other local path the file's name, and no credential is left. + */ +export function readableSummary(text: string, folders: string[]): string { + const unlinked = text.replace( + MARKDOWN_LINK, + (link, label: string, target: string) => + WEB_ADDRESS.test(target) ? link : label, + ); + const inProject = folders.reduce( + (written, folder) => + written + .split(`${folder}/`) + .join("") + .split(`${encodeURI(folder)}/`) + .join(""), + unlinked, + ); + return publicText(inProject).replace(PATH_IN_A_HOME, "$1").trim(); +} diff --git a/runtime/sharing/cards/worker-messages.ts b/runtime/sharing/cards/worker-messages.ts new file mode 100644 index 0000000..abb757a --- /dev/null +++ b/runtime/sharing/cards/worker-messages.ts @@ -0,0 +1,146 @@ +import type { Message } from "../../../src/shared"; +import type { WorkerInputRequest } from "../../../src/worker-input"; +import { publicText, type DeliveryRecord, type InputRecord } from "./entries"; + +/** Who runs the worker a message is for, in the words the sender reads. */ +export interface Host { + /** The person who started the worker. */ + name: string; + /** "Mac", "Windows" or "Linux". */ + device: string; + /** The worker runs under the account signed in here: the person's own other computer. */ + isYou: boolean; +} + +const thereOf = (host: Host) => + host.isYou ? `your ${host.device}` : `${host.name}'s ${host.device}`; + +/** + * How a message sent to a worker on another computer stands, as its sender and + * everyone else on the card read it. Only a delivery by the account that + * started the worker is passed in. + */ +export function messageStanding( + delivery: DeliveryRecord | undefined, + host: Host, + sending: boolean, +): Pick { + if (sending) return { followupState: "queued", deliveryLine: "Sending…" }; + switch (delivery?.state) { + case undefined: + return { + followupState: "queued", + deliveryLine: `Sent to ${thereOf(host)}`, + }; + case "asking": + return { + followupState: "queued", + deliveryLine: `Waiting for ${host.name} to allow it`, + }; + case "queued": + return { + followupState: "queued", + deliveryLine: host.isYou + ? `Queued on your ${host.device}` + : `${host.name} allowed it`, + }; + case "picked-up": + return { followupState: "included", pickedUpAt: delivery.at }; + case "declined": + return { + followupState: "cancelled", + deliveryLine: `${host.name} declined`, + }; + case "failed": + return { + followupState: "paused", + deliveryLine: delivery.detail + ? `Not delivered: ${delivery.detail}` + : `Could not reach the worker on ${thereOf(host)}`, + }; + } +} + +/** Where an answer to what a worker waits for stands, for the panel that asked. */ +export function answerStanding( + delivery: DeliveryRecord | undefined, + host: Host, + sending: boolean, +): NonNullable { + const standing = messageStanding(delivery, host, sending); + return { + line: + delivery?.state === "picked-up" + ? `Answered from here` + : standing.deliveryLine, + // Declined or not delivered: the person may answer again. + answerable: delivery?.state === "declined" || delivery?.state === "failed", + }; +} + +const TITLE = 4000, + TEXT = 8000; +const cut = (text: string | undefined, length: number) => + text === undefined ? undefined : publicText(text).slice(0, length); + +/** What a worker run here waits for, as other computers may see it. */ +export function inputRecordOf( + input: WorkerInputRequest, + sessionId: string, +): InputRecord { + const secret = input.questions?.some((question) => question.secret); + const record: InputRecord = { + sessionId, + id: input.id, + kind: input.kind, + title: cut(input.title, TITLE)!, + description: cut(input.description, TEXT), + toolName: input.toolName?.slice(0, 200), + details: cut(input.details, TEXT), + options: input.options?.slice(0, 40).map((option) => ({ + id: option.id.slice(0, 1000), + label: option.label.slice(0, 500), + ...(option.description + ? { description: cut(option.description, 2000) } + : {}), + ...(option.kind ? { kind: option.kind } : {}), + })), + questions: input.questions?.slice(0, 20).map((question) => ({ + id: question.id.slice(0, 1000), + question: cut(question.question, TITLE)!, + options: question.options.slice(0, 40).map((option) => ({ + id: option.id.slice(0, 1000), + label: option.label.slice(0, 500), + ...(option.kind ? { kind: option.kind } : {}), + })), + ...(question.multiple ? { multiple: true } : {}), + ...(question.allowText ? { allowText: true } : {}), + ...(question.secret ? { secret: true } : {}), + })), + createdAt: input.createdAt, + status: input.status, + ...(secret ? { answerHere: true } : {}), + }; + return JSON.parse(JSON.stringify(record)); +} + +/** One line for an answer, for the person asked to allow it. */ +export function answerSummary( + input: WorkerInputRequest | undefined, + response: { optionId?: string; answers?: Record }, +): string { + if (!input) return "An answer to what the worker asked"; + const chosen = input.options?.find( + (option) => option.id === response.optionId, + ); + if (chosen) return `${input.title}: ${chosen.label}`; + const answers = (input.questions ?? []).map((question) => { + const value = response.answers?.[question.id]; + const labels = (Array.isArray(value) ? value : [value ?? ""]).map( + (one) => + question.options.find((option) => option.id === one)?.label ?? one, + ); + return `${question.question}: ${labels.join(", ")}`; + }); + return answers.length ? answers.join("\n") : input.title; +} diff --git a/runtime/sharing/discovery.ts b/runtime/sharing/discovery.ts new file mode 100644 index 0000000..085bcf9 --- /dev/null +++ b/runtime/sharing/discovery.ts @@ -0,0 +1,90 @@ +import type { SharingSettings } from "../../src/sharing"; +import { BETA_ORIGIN } from "../beta-auth"; + +/** + * Where MemCode finds the sharing service: in memtrace.io's list of MemCode + * services, the same list Team Sync reads, under `sharing`. A list without it + * means sharing is not offered, and MemCode shows no Share button. + * + * For tests and a local demo only, two environment variables name local + * servers instead. No screen offers them. + */ +export const DEVELOPER_SHARING_SERVICE = "MEMCODE_DEV_SHARING_SERVICE", + DEVELOPER_SHARING_TOKEN_ADDRESS = "MEMCODE_DEV_SHARING_TOKEN_ADDRESS"; +const SERVICES_PATH = "/api/memcode/services"; +const LONGEST_LIST = 16 * 1024, + KEPT_FOR_MS = 60_000; + +export interface SharingFinderOptions { + fetcher?: typeof fetch; + environment?: NodeJS.ProcessEnv; + now?: () => number; +} + +async function readList(fetcher: typeof fetch): Promise { + // Public: nothing about the person or their projects is sent. + const response = await fetcher(BETA_ORIGIN + SERVICES_PATH, { + redirect: "error", + signal: AbortSignal.timeout(5000), + headers: { accept: "application/json" }, + }); + if (!response.ok) + throw new Error(`The service list answered ${response.status}.`); + const text = await response.text(); + if (text.length > LONGEST_LIST) + throw new Error("The service list is too long."); + return JSON.parse(text); +} + +/** The sharing addresses in a service list, or nothing when sharing is not offered. */ +export function sharingInList(list: unknown): SharingSettings | undefined { + const read = list as { version?: unknown; sharing?: unknown } | null; + if (!read || read.version !== 1) + throw new Error("The service list is not one MemCode reads."); + if (read.sharing === undefined || read.sharing === null) return undefined; + const sharing = read.sharing as { + endpoint?: unknown; + tokenEndpoint?: unknown; + }; + if ( + typeof sharing.endpoint !== "string" || + typeof sharing.tokenEndpoint !== "string" + ) + throw new Error( + "The service list names sharing without its two addresses.", + ); + return { memsyncUrl: sharing.endpoint, tokenUrl: sharing.tokenEndpoint }; +} + +/** Finds the sharing service when asked, at most once a minute. */ +export function sharingFinder(options: SharingFinderOptions = {}) { + const fetcher = options.fetcher ?? fetch, + environment = options.environment ?? process.env, + now = options.now ?? Date.now; + let kept: { until: number; value: SharingSettings | undefined } | undefined; + let finding: Promise | undefined; + return (): Promise => { + const service = environment[DEVELOPER_SHARING_SERVICE], + tokenAddress = environment[DEVELOPER_SHARING_TOKEN_ADDRESS]; + if (service && tokenAddress) + return Promise.resolve({ memsyncUrl: service, tokenUrl: tokenAddress }); + if (kept && kept.until > now()) return Promise.resolve(kept.value); + finding ??= readList(fetcher) + .then(sharingInList) + .catch((problem) => { + console.error( + "[sharing] The sharing service could not be found:", + problem, + ); + return undefined; + }) + .then((value) => { + kept = { until: now() + KEPT_FOR_MS, value }; + return value; + }) + .finally(() => { + finding = undefined; + }); + return finding; + }; +} diff --git a/runtime/sharing/memsync/boards-api.ts b/runtime/sharing/memsync/boards-api.ts new file mode 100644 index 0000000..05d9825 --- /dev/null +++ b/runtime/sharing/memsync/boards-api.ts @@ -0,0 +1,112 @@ +import { + boardsCalls, + boardsContract, + boardsService, + type BoardsCall, +} from "./boards-contract"; +import type { GrpcStream } from "./grpc"; +import type { ServiceCall, SignedCalls } from "./signed-calls"; +import { WireError, type WireMessage } from "./wire"; + +/** One change to a board, as its sender made it. The service never reads the bytes. */ +export interface NewBoardUpdate { + /** A UUID the sender chooses. Sending the same id again adds nothing. */ + id: string; + payload: Uint8Array; +} +export interface UpdateReceipt { + id: string; + /** Its place in the project's log, from 1 with no gaps. */ + sequence: number; + loggedAt: string; +} +export interface LoggedUpdate extends UpdateReceipt { + /** The account that sent it. */ + author: string; + payload: Uint8Array; +} + +/** A project's board log at the sharing service. */ +export interface BoardsApi { + /** Adds updates to the end of the log: at most 100, each at most 1 MiB. */ + append( + projectId: string, + updates: NewBoardUpdate[], + ): Promise; + /** The next page after a number, oldest first. An empty page: nothing newer. */ + readAfter(projectId: string, sequence: number): Promise; + /** Everything after a number, then each new update as it is logged. */ + watchAfter( + projectId: string, + sequence: number, + onUpdate: (update: LoggedUpdate) => void | Promise, + ): GrpcStream; +} + +const unreadable = () => + new WireError("A board update lacks something it always holds."); +const isMessage = (value: unknown): value is WireMessage => + !!value && typeof value === "object" && !Array.isArray(value); +const messages = (value: unknown) => (Array.isArray(value) ? value : []); + +function receipt(sent: WireMessage): UpdateReceipt { + const when = sent.logged_at; + if (!sent.id || !Number(sent.sequence) || !isMessage(when)) + throw unreadable(); + const loggedAt = new Date( + Number(when.seconds) * 1000 + Number(when.nanos) / 1e6, + ); + if (Number.isNaN(loggedAt.getTime())) throw unreadable(); + return { + id: String(sent.id), + sequence: Number(sent.sequence), + loggedAt: loggedAt.toISOString(), + }; +} + +function logged(sent: WireMessage): LoggedUpdate { + if (!(sent.payload instanceof Uint8Array)) throw unreadable(); + return { + ...receipt(sent), + author: String(sent.author_account_id), + payload: sent.payload, + }; +} + +const call = (name: BoardsCall): ServiceCall => ({ + service: boardsService, + name, + contract: boardsContract, + ...boardsCalls[name], +}); + +/** The Boards API over gRPC, signed in with the caller's access token. */ +export class MemsyncBoards implements BoardsApi { + constructor(private readonly calls: SignedCalls) {} + + append(projectId: string, updates: NewBoardUpdate[]) { + const request = { + project_id: projectId, + updates: updates.map(({ id, payload }) => ({ id, payload })), + }; + return this.calls.unary(call("AppendUpdates"), request, (reply) => + messages(reply.receipts).map(receipt), + ); + } + readAfter(projectId: string, sequence: number) { + const request = { project_id: projectId, after_sequence: sequence }; + return this.calls.unary(call("ReadUpdates"), request, (reply) => + messages(reply.updates).map(logged), + ); + } + watchAfter( + projectId: string, + sequence: number, + onUpdate: (update: LoggedUpdate) => void | Promise, + ) { + const request = { project_id: projectId, after_sequence: sequence }; + return this.calls.stream(call("WatchUpdates"), request, (update) => + onUpdate(logged(update)), + ); + } +} diff --git a/runtime/sharing/memsync/boards-contract.ts b/runtime/sharing/memsync/boards-contract.ts new file mode 100644 index 0000000..d23d3ab --- /dev/null +++ b/runtime/sharing/memsync/boards-contract.ts @@ -0,0 +1,51 @@ +import type { Contract } from "./wire"; + +/** + * boards.proto, written out by hand. A test reads the .proto file beside this one + * and fails when the two disagree. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +const bytes = (number: number) => ({ number, kind: "bytes" }) as const; +const count = (number: number) => ({ number, kind: "uint64" }) as const; +const moment = "google.protobuf.Timestamp"; +const loggedAt = (number: number) => + ({ number, kind: { message: moment } }) as const; +const many = (number: number, message: string) => + ({ number, kind: { message }, repeated: true }) as const; + +export const boardsService = "memsync.v1.Boards"; + +export const boardsContract = { + [moment]: { + seconds: { number: 1, kind: "int64" }, + nanos: { number: 2, kind: "int32" }, + }, + NewBoardUpdate: { id: text(1), payload: bytes(2) }, + BoardUpdate: { + id: text(1), + sequence: count(2), + logged_at: loggedAt(3), + author_account_id: text(4), + payload: bytes(5), + }, + UpdateReceipt: { id: text(1), sequence: count(2), logged_at: loggedAt(3) }, + AppendUpdatesRequest: { + project_id: text(1), + updates: many(2, "NewBoardUpdate"), + }, + AppendUpdatesResponse: { receipts: many(1, "UpdateReceipt") }, + ReadUpdatesRequest: { project_id: text(1), after_sequence: count(2) }, + ReadUpdatesResponse: { updates: many(1, "BoardUpdate") }, + WatchUpdatesRequest: { project_id: text(1), after_sequence: count(2) }, +} satisfies Contract; + +export const boardsCalls = { + AppendUpdates: { + request: "AppendUpdatesRequest", + reply: "AppendUpdatesResponse", + }, + ReadUpdates: { request: "ReadUpdatesRequest", reply: "ReadUpdatesResponse" }, + /** The reply is a stream of these, one per update. */ + WatchUpdates: { request: "WatchUpdatesRequest", reply: "BoardUpdate" }, +} as const; +export type BoardsCall = keyof typeof boardsCalls; diff --git a/runtime/sharing/memsync/boards.proto b/runtime/sharing/memsync/boards.proto new file mode 100644 index 0000000..3219aba --- /dev/null +++ b/runtime/sharing/memsync/boards.proto @@ -0,0 +1,78 @@ +syntax = "proto3"; + +package memsync.v1; + +import "google/protobuf/timestamp.proto"; + +// A project's board, kept in step between computers. +// +// The board is one Yjs document. MemSync keeps its updates in a log: every update gets +// the next number in its project's log and the time the server logged it, once. +// Applying a log in order gives every computer the same board and the same dates. +// MemSync never looks inside an update, so a caller must cope with one it cannot apply. +// +// Calls are signed in and turned down as in the Projects service. Anyone on the project +// can read and add. +service Boards { + // Adds updates to the end of the project's board log. An update whose id is already + // in the log is not added again, so a call can be sent again when its answer was lost. + rpc AppendUpdates(AppendUpdatesRequest) returns (AppendUpdatesResponse); + // Reads the next page of the log after a number, oldest first. An empty page means + // there is nothing newer. + rpc ReadUpdates(ReadUpdatesRequest) returns (ReadUpdatesResponse); + // Sends everything in the log after a number, then every new update as it is logged, + // until the caller hangs up or is no longer on the project. + rpc WatchUpdates(WatchUpdatesRequest) returns (stream BoardUpdate); +} + +message NewBoardUpdate { + // A UUID chosen by the sender. Sending the same id again adds nothing. + string id = 1; + // One Yjs update in the v1 encoding, at most 1 MiB. + bytes payload = 2; +} + +message BoardUpdate { + string id = 1; + // Its place in the project's log, from 1, with no gaps. + uint64 sequence = 2; + // When MemSync logged it. Never earlier than the update before it. + google.protobuf.Timestamp logged_at = 3; + // The `Person.account_id` of whoever sent it. + string author_account_id = 4; + bytes payload = 5; +} + +message UpdateReceipt { + string id = 1; + uint64 sequence = 2; + google.protobuf.Timestamp logged_at = 3; +} + +message AppendUpdatesRequest { + string project_id = 1; + // At most 100, and together small enough for one gRPC message: 4 MiB unless the + // server is set up otherwise. Send a large first sync in several calls. + repeated NewBoardUpdate updates = 2; +} + +message AppendUpdatesResponse { + // One for each update sent, in the order sent. + repeated UpdateReceipt receipts = 1; +} + +message ReadUpdatesRequest { + string project_id = 1; + // 0 reads from the start. + uint64 after_sequence = 2; +} + +message ReadUpdatesResponse { + repeated BoardUpdate updates = 1; +} + +message WatchUpdatesRequest { + string project_id = 1; + // 0 watches from the start. + uint64 after_sequence = 2; +} diff --git a/runtime/sharing/memsync/cards-api.ts b/runtime/sharing/memsync/cards-api.ts new file mode 100644 index 0000000..0280b1c --- /dev/null +++ b/runtime/sharing/memsync/cards-api.ts @@ -0,0 +1,169 @@ +import type { LoggedUpdate, UpdateReceipt } from "./boards-api"; +import { + cardReaders, + cardsCalls, + cardsContract, + cardsService, + type CardReaders, + type CardsCall, +} from "./cards-contract"; +import type { GrpcStream } from "./grpc"; +import type { ServiceCall, SignedCalls } from "./signed-calls"; +import { WireError, type WireMessage } from "./wire"; + +/** One entry of a card's activity log, as its sender made it. The service never reads it. */ +export interface NewCardEntry { + /** A UUID the sender chooses. Sending the same id again to the same card adds nothing. */ + id: string; + payload: Uint8Array; + /** Everyone on the project, the default, or only the account that sends it. */ + readers?: CardReaders; +} +/** An entry as the log holds it: numbered, dated and signed by the service. */ +export type LoggedCardEntry = LoggedUpdate; + +/** A file the project keeps, by the SHA-256 of its bytes. */ +export interface StoredFile { + sha256: string; + size: number; + uploadedBy: string; + uploadedAt: string; +} + +/** The activity logs of a project's cards, and the files they refer to. */ +export interface CardsApi { + /** Adds entries to the end of a card's log: at most 100, each at most 1 MiB. */ + append( + projectId: string, + cardId: string, + entries: NewCardEntry[], + ): Promise; + /** The next page of a card's log after a number. An empty page: nothing newer. */ + readAfter( + projectId: string, + cardId: string, + sequence: number, + ): Promise; + /** Everything after a number, then each new entry as it is logged. */ + watchAfter( + projectId: string, + cardId: string, + sequence: number, + onEntry: (entry: LoggedCardEntry) => void | Promise, + ): GrpcStream; + /** Keeps a file for the project: at most 5 MiB. Sending it again adds nothing. */ + upload(projectId: string, content: Uint8Array): Promise; + download( + projectId: string, + sha256: string, + ): Promise<{ file: StoredFile; content: Uint8Array }>; +} + +const unreadable = () => + new WireError("A card's log or file lacks something it always holds."); +const isMessage = (value: unknown): value is WireMessage => + !!value && typeof value === "object" && !Array.isArray(value); +const messages = (value: unknown) => (Array.isArray(value) ? value : []); +const sha256Shape = /^[0-9a-f]{64}$/; + +function moment(value: unknown): string { + if (!isMessage(value)) throw unreadable(); + const when = new Date( + Number(value.seconds) * 1000 + Number(value.nanos) / 1e6, + ); + if (Number.isNaN(when.getTime())) throw unreadable(); + return when.toISOString(); +} + +function receipt(sent: WireMessage): UpdateReceipt { + if (!sent.id || !Number(sent.sequence)) throw unreadable(); + return { + id: String(sent.id), + sequence: Number(sent.sequence), + loggedAt: moment(sent.logged_at), + }; +} + +function logged(sent: WireMessage): LoggedCardEntry { + if (!(sent.payload instanceof Uint8Array) || !sent.author_account_id) + throw unreadable(); + return { + ...receipt(sent), + author: String(sent.author_account_id), + payload: sent.payload, + }; +} + +function stored(sent: unknown): StoredFile { + if (!isMessage(sent) || !sha256Shape.test(String(sent.sha256))) + throw unreadable(); + return { + sha256: String(sent.sha256), + size: Number(sent.size), + uploadedBy: String(sent.uploaded_by_account_id), + uploadedAt: moment(sent.uploaded_at), + }; +} + +const call = (name: CardsCall): ServiceCall => ({ + service: cardsService, + name, + contract: cardsContract, + ...cardsCalls[name], +}); + +/** The Cards API over gRPC, signed in with the caller's access token. */ +export class MemsyncCards implements CardsApi { + constructor(private readonly calls: SignedCalls) {} + + append(projectId: string, cardId: string, entries: NewCardEntry[]) { + const request = { + project_id: projectId, + card_id: cardId, + entries: entries.map(({ id, payload, readers = "everyone" }) => ({ + id, + payload, + readers: cardReaders[readers], + })), + }; + return this.calls.unary(call("AppendCardEntries"), request, (reply) => + messages(reply.receipts).map(receipt), + ); + } + readAfter(projectId: string, cardId: string, sequence: number) { + const request = { + project_id: projectId, + card_id: cardId, + after_sequence: sequence, + }; + return this.calls.unary(call("ReadCardEntries"), request, (reply) => + messages(reply.entries).map(logged), + ); + } + watchAfter( + projectId: string, + cardId: string, + sequence: number, + onEntry: (entry: LoggedCardEntry) => void | Promise, + ) { + const request = { + project_id: projectId, + card_id: cardId, + after_sequence: sequence, + }; + return this.calls.stream(call("WatchCardEntries"), request, (entry) => + onEntry(logged(entry)), + ); + } + upload(projectId: string, content: Uint8Array) { + const request = { project_id: projectId, content }; + return this.calls.unary(call("UploadFile"), request, stored); + } + download(projectId: string, sha256: string) { + const request = { project_id: projectId, sha256 }; + return this.calls.unary(call("DownloadFile"), request, (reply) => { + if (!(reply.content instanceof Uint8Array)) throw unreadable(); + return { file: stored(reply.file), content: reply.content }; + }); + } +} diff --git a/runtime/sharing/memsync/cards-contract.ts b/runtime/sharing/memsync/cards-contract.ts new file mode 100644 index 0000000..e2d9abb --- /dev/null +++ b/runtime/sharing/memsync/cards-contract.ts @@ -0,0 +1,91 @@ +import type { Contract } from "./wire"; + +/** + * cards.proto, written out by hand. A test reads the .proto file beside this one + * and fails when the two disagree. `UpdateReceipt` comes from boards.proto. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +const bytes = (number: number) => ({ number, kind: "bytes" }) as const; +const count = (number: number) => ({ number, kind: "uint64" }) as const; +/** An enum travels as an int32. */ +const choice = (number: number) => ({ number, kind: "int32" }) as const; +const moment = "google.protobuf.Timestamp"; +const at = (number: number) => ({ number, kind: { message: moment } }) as const; +const one = (number: number, message: string) => + ({ number, kind: { message } }) as const; +const many = (number: number, message: string) => + ({ number, kind: { message }, repeated: true }) as const; + +export const cardsService = "memsync.v1.Cards"; + +/** Who may read a card entry (MemSync ADR-0019), as the `Readers` enum numbers it. */ +export const cardReaders = { + everyone: 0, + "only-its-author": 1, +} as const; +export type CardReaders = keyof typeof cardReaders; + +export const cardsContract = { + [moment]: { + seconds: { number: 1, kind: "int64" }, + nanos: { number: 2, kind: "int32" }, + }, + UpdateReceipt: { id: text(1), sequence: count(2), logged_at: at(3) }, + NewCardEntry: { id: text(1), payload: bytes(2), readers: choice(3) }, + CardEntry: { + id: text(1), + sequence: count(2), + logged_at: at(3), + author_account_id: text(4), + payload: bytes(5), + readers: choice(6), + }, + AppendCardEntriesRequest: { + project_id: text(1), + card_id: text(2), + entries: many(3, "NewCardEntry"), + }, + AppendCardEntriesResponse: { receipts: many(1, "UpdateReceipt") }, + ReadCardEntriesRequest: { + project_id: text(1), + card_id: text(2), + after_sequence: count(3), + }, + ReadCardEntriesResponse: { entries: many(1, "CardEntry") }, + WatchCardEntriesRequest: { + project_id: text(1), + card_id: text(2), + after_sequence: count(3), + }, + UploadFileRequest: { project_id: text(1), content: bytes(2) }, + StoredFile: { + sha256: text(1), + size: count(2), + uploaded_by_account_id: text(3), + uploaded_at: at(4), + }, + DownloadFileRequest: { project_id: text(1), sha256: text(2) }, + DownloadFileResponse: { file: one(1, "StoredFile"), content: bytes(2) }, +} satisfies Contract; + +export const cardsCalls = { + AppendCardEntries: { + request: "AppendCardEntriesRequest", + reply: "AppendCardEntriesResponse", + }, + ReadCardEntries: { + request: "ReadCardEntriesRequest", + reply: "ReadCardEntriesResponse", + }, + /** The reply is a stream of these, one per entry. */ + WatchCardEntries: { request: "WatchCardEntriesRequest", reply: "CardEntry" }, + UploadFile: { request: "UploadFileRequest", reply: "StoredFile" }, + DownloadFile: { + request: "DownloadFileRequest", + reply: "DownloadFileResponse", + }, +} as const; +export type CardsCall = keyof typeof cardsCalls; + +/** A message of this service is at most this large, a whole file included. */ +export const LARGEST_CARDS_MESSAGE = 6 * 1024 * 1024; diff --git a/runtime/sharing/memsync/cards.proto b/runtime/sharing/memsync/cards.proto new file mode 100644 index 0000000..e883e6b --- /dev/null +++ b/runtime/sharing/memsync/cards.proto @@ -0,0 +1,120 @@ +syntax = "proto3"; + +package memsync.v1; + +import "google/protobuf/timestamp.proto"; +import "memsync/v1/boards.proto"; + +// What happened on a card: the worker conversations, reviews and results MemCode writes +// there, and the files they refer to. +// +// Each card has its own log. Every entry gets the next number in that card's log, the +// time MemSync logged it and the account that sent it, once. MemSync never looks inside +// an entry. A file is kept per project under the SHA-256 of its bytes. +// +// Calls are signed in and turned down as in the Projects service. Anyone on the project +// can add, and read everything but the entries only their author reads (ADR-0019). +// Messages of this service may be up to 6 MiB. +service Cards { + // Adds entries to the end of a card's log. An entry whose id is already in that log + // is not added again, so a call can be sent again when its answer was lost. + rpc AppendCardEntries(AppendCardEntriesRequest) returns (AppendCardEntriesResponse); + // Reads the next page of a card's log after a number, oldest first. An empty page + // means there is nothing newer. + rpc ReadCardEntries(ReadCardEntriesRequest) returns (ReadCardEntriesResponse); + // Sends everything in a card's log after a number, then every new entry as it is + // logged, until the caller hangs up or is no longer on the project. + rpc WatchCardEntries(WatchCardEntriesRequest) returns (stream CardEntry); + // Keeps a file for the project. Sending a file the project already has adds nothing. + rpc UploadFile(UploadFileRequest) returns (StoredFile); + // Hands back a file the project keeps. + rpc DownloadFile(DownloadFileRequest) returns (DownloadFileResponse); +} + +// Who may read an entry of a card's log. +enum Readers { + // Everyone on the project. + READERS_EVERYONE = 0; + // Only the account that sent it, on any of its computers. Reading and watching leave it + // out for everyone else, so the numbers they see have gaps where it is. + READERS_ONLY_ITS_AUTHOR = 1; +} + +message NewCardEntry { + // A UUID chosen by the sender. Sending the same id again to the same card adds nothing, + // and does not change who reads it. + string id = 1; + // MemCode's own record, at most 1 MiB. MemSync does not read it. + bytes payload = 2; + // Any other value is turned down. + Readers readers = 3; +} + +message CardEntry { + string id = 1; + // Its place in the card's log, from 1. The log has no gaps, but a reader sees one where + // an entry only its author reads was left out. + uint64 sequence = 2; + // When MemSync logged it. Never earlier than the entry before it. + google.protobuf.Timestamp logged_at = 3; + // The `Person.account_id` of whoever sent it. + string author_account_id = 4; + bytes payload = 5; + Readers readers = 6; +} + +message AppendCardEntriesRequest { + string project_id = 1; + // MemCode's id of the card: a UUID. + string card_id = 2; + // At most 100. + repeated NewCardEntry entries = 3; +} + +message AppendCardEntriesResponse { + // One for each entry sent, in the order sent. + repeated UpdateReceipt receipts = 1; +} + +message ReadCardEntriesRequest { + string project_id = 1; + string card_id = 2; + // 0 reads from the start. + uint64 after_sequence = 3; +} + +message ReadCardEntriesResponse { + repeated CardEntry entries = 1; +} + +message WatchCardEntriesRequest { + string project_id = 1; + string card_id = 2; + // 0 watches from the start. + uint64 after_sequence = 3; +} + +message UploadFileRequest { + string project_id = 1; + // At most 5 MiB. A project keeps at most 50 MiB of files. + bytes content = 2; +} + +message StoredFile { + // The SHA-256 of the content, 64 lower-case hex digits. + string sha256 = 1; + uint64 size = 2; + // The `Person.account_id` of whoever uploaded it first. + string uploaded_by_account_id = 3; + google.protobuf.Timestamp uploaded_at = 4; +} + +message DownloadFileRequest { + string project_id = 1; + string sha256 = 2; +} + +message DownloadFileResponse { + StoredFile file = 1; + bytes content = 2; +} diff --git a/runtime/sharing/memsync/grpc.ts b/runtime/sharing/memsync/grpc.ts new file mode 100644 index 0000000..e0340ec --- /dev/null +++ b/runtime/sharing/memsync/grpc.ts @@ -0,0 +1,519 @@ +import { + connect, + constants, + type ClientHttp2Session, + type IncomingHttpHeaders, +} from "node:http2"; + +/** gRPC's status codes, by the names the protocol gives them. */ +export const grpcStatus = { + OK: 0, + CANCELLED: 1, + UNKNOWN: 2, + INVALID_ARGUMENT: 3, + DEADLINE_EXCEEDED: 4, + NOT_FOUND: 5, + ALREADY_EXISTS: 6, + PERMISSION_DENIED: 7, + RESOURCE_EXHAUSTED: 8, + FAILED_PRECONDITION: 9, + ABORTED: 10, + OUT_OF_RANGE: 11, + UNIMPLEMENTED: 12, + INTERNAL: 13, + UNAVAILABLE: 14, + DATA_LOSS: 15, + UNAUTHENTICATED: 16, +} as const; + +/** A call that did not end in a reply: the service's own status, or one this client gave it. */ +export class GrpcFailure extends Error { + constructor( + readonly code: number, + message: string, + readonly metadata: Readonly> = {}, + ) { + super(message); + this.name = "GrpcFailure"; + } +} + +export interface GrpcCall { + /** `/package.Service/Method`. */ + path: string; + request: Uint8Array; + metadata?: Record; + timeoutMs?: number; +} +/** A call the service keeps answering until it ends the call or the caller hangs up. */ +export interface GrpcStream { + /** Settles when the stream is over: rejects with what ended it, unless the caller hung up. */ + finished: Promise; + cancel(): void; +} +export interface GrpcChannel { + /** One request, one reply. */ + unary(call: GrpcCall): Promise; + /** + * One request, then a message at a time for as long as the service sends them. + * `timeoutMs` is how long the service may take to begin. Messages are handed + * over in order, the next one only when the one before has been dealt with. + */ + serverStream( + call: GrpcCall, + onMessage: (message: Uint8Array) => void | Promise, + ): GrpcStream; + close(): void; +} +export interface GrpcChannelOptions { + /** How long an unused connection is kept. A stale one is the usual way a call hangs. */ + idleMs?: number; + maxReplyBytes?: number; + /** How often a connection with an open stream is asked whether it is still there. */ + keepAliveMs?: number; +} + +const FRAME_HEADER_BYTES = 5, + NOT_COMPRESSED = 0; +const DEFAULT_TIMEOUT_MS = 10_000, + DEFAULT_IDLE_MS = 10_000, + DEFAULT_KEEP_ALIVE_MS = 20_000, + // A stream can be silent for hours, so a lost connection shows only when asked. + KEEP_ALIVE_PATIENCE_MS = 10_000, + // Messages read ahead of a slow reader before the service is asked to wait. + HELD_FOR_A_SLOW_READER = 32, + // What a gRPC server sends at most unless it is set up otherwise. + DEFAULT_MAX_REPLY_BYTES = 4 * 1024 * 1024; + +function frame(message: Uint8Array): Buffer { + const framed = Buffer.alloc(FRAME_HEADER_BYTES + message.length); + framed[0] = NOT_COMPRESSED; + framed.writeUInt32BE(message.length, 1); + framed.set(message, FRAME_HEADER_BYTES); + return framed; +} + +/** A reply to a unary call is exactly one uncompressed message. */ +function soleMessage(body: Buffer): Uint8Array | GrpcFailure { + const unreadable = (what: string) => + new GrpcFailure( + grpcStatus.INTERNAL, + `The sharing service sent a reply that ${what}.`, + ); + if (body.length < FRAME_HEADER_BYTES) return unreadable("holds no message"); + if (body[0] !== NOT_COMPRESSED) return unreadable("is compressed"); + const length = body.readUInt32BE(1); + if (body.length < FRAME_HEADER_BYTES + length) + return unreadable("is cut short"); + if (body.length > FRAME_HEADER_BYTES + length) + return unreadable("holds more than one message"); + return new Uint8Array(body.subarray(FRAME_HEADER_BYTES)); +} + +function metadataFrom(headers: IncomingHttpHeaders | undefined) { + const metadata: Record = {}; + for (const [name, value] of Object.entries(headers ?? {})) + if (!name.startsWith(":") && value !== undefined) + metadata[name] = Array.isArray(value) ? value.join(", ") : value; + return metadata; +} + +function reasonSent(encoded: string | undefined): string { + if (!encoded) return "The sharing service turned the call down."; + try { + return decodeURIComponent(encoded); + } catch { + return encoded; + } +} + +/** What a proxy means when it answers itself, as gRPC maps HTTP statuses. */ +function statusOfHttp(http: number): number { + if (http === 401) return grpcStatus.UNAUTHENTICATED; + if (http === 403) return grpcStatus.PERMISSION_DENIED; + if (http === 404) return grpcStatus.UNIMPLEMENTED; + if ([429, 502, 503, 504].includes(http)) return grpcStatus.UNAVAILABLE; + return grpcStatus.UNKNOWN; +} + +interface Received { + headers?: IncomingHttpHeaders; + trailers?: IncomingHttpHeaders; + body: Buffer[]; + bytes: number; +} + +function withoutStatus( + headers: IncomingHttpHeaders, + metadata: Record, +) { + const http = Number(headers[":status"]); + if (http !== 200) + return new GrpcFailure( + statusOfHttp(http), + `The address answered HTTP ${http} instead of a sharing reply.`, + metadata, + ); + if (!String(headers["content-type"] ?? "").startsWith("application/grpc")) + return new GrpcFailure( + grpcStatus.UNKNOWN, + "The address answered, but it is not a sharing service.", + metadata, + ); + return new GrpcFailure( + grpcStatus.UNAVAILABLE, + "The connection was cut before the sharing service finished its answer.", + metadata, + ); +} + +/** Why the call did not succeed, or nothing when the service said it did. */ +function failureOf({ headers, trailers }: Received): GrpcFailure | undefined { + if (!headers) + return new GrpcFailure( + grpcStatus.UNAVAILABLE, + "The sharing service closed the connection before it answered.", + ); + // A call that is turned down at once carries its status in the first headers. + const metadata = { ...metadataFrom(headers), ...metadataFrom(trailers) }; + const status = metadata["grpc-status"]; + if (status === undefined) return withoutStatus(headers, metadata); + const code = Number(status); + if (code === grpcStatus.OK) return undefined; + return new GrpcFailure( + Number.isInteger(code) ? code : grpcStatus.UNKNOWN, + reasonSent(metadata["grpc-message"]), + metadata, + ); +} + +const outcome = (received: Received): Uint8Array | GrpcFailure => + failureOf(received) ?? soleMessage(Buffer.concat(received.body)); + +/** The first whole message in what has arrived so far, or nothing when more bytes are needed. */ +function nextMessage( + arrived: Buffer, + maxMessageBytes: number, +): { message: Uint8Array; rest: Buffer } | GrpcFailure | undefined { + if (arrived.length < FRAME_HEADER_BYTES) return undefined; + if (arrived[0] !== NOT_COMPRESSED) + return new GrpcFailure( + grpcStatus.INTERNAL, + "The sharing service sent a message that is compressed.", + ); + const end = FRAME_HEADER_BYTES + arrived.readUInt32BE(1); + if (end - FRAME_HEADER_BYTES > maxMessageBytes) + return new GrpcFailure( + grpcStatus.RESOURCE_EXHAUSTED, + "The sharing service sent a larger message than MemCode reads.", + ); + if (arrived.length < end) return undefined; + return { + message: new Uint8Array(arrived.subarray(FRAME_HEADER_BYTES, end)), + rest: arrived.subarray(end), + }; +} + +const notReached = (error: unknown) => + new GrpcFailure( + grpcStatus.UNAVAILABLE, + `The sharing service could not be reached (${ + (error as NodeJS.ErrnoException).code ?? (error as Error).message + }).`, + ); + +function exchange( + session: ClientHttp2Session, + path: string, + call: GrpcCall, + maxReplyBytes: number, +): Promise { + const timeoutMs = call.timeoutMs ?? DEFAULT_TIMEOUT_MS; + return new Promise((resolve, reject) => { + const received: Received = { body: [], bytes: 0 }; + const stream = session.request({ + ...call.metadata, + ":method": "POST", + ":path": path, + "content-type": "application/grpc", + te: "trailers", + "grpc-timeout": `${timeoutMs}m`, + }); + let finished = false; + const finish = (result: Uint8Array | GrpcFailure) => { + if (finished) return; + finished = true; + clearTimeout(deadline); + if (!(result instanceof GrpcFailure)) return resolve(result); + stream.close(constants.NGHTTP2_CANCEL); + reject(result); + }; + const deadline = setTimeout( + () => + finish( + new GrpcFailure( + grpcStatus.DEADLINE_EXCEEDED, + "The sharing service did not answer in time.", + ), + ), + timeoutMs, + ); + stream.on("response", (headers) => (received.headers = headers)); + stream.on("trailers", (trailers) => (received.trailers = trailers)); + stream.on("data", (part: Buffer) => { + received.bytes += part.length; + if (received.bytes <= maxReplyBytes + FRAME_HEADER_BYTES) + return void received.body.push(part); + finish( + new GrpcFailure( + grpcStatus.RESOURCE_EXHAUSTED, + "The sharing service sent a larger reply than MemCode reads.", + ), + ); + }); + stream.on("error", (error) => finish(notReached(error))); + stream.on("close", () => finish(outcome(received))); + stream.end(frame(call.request)); + }); +} + +function follow( + session: ClientHttp2Session, + path: string, + call: GrpcCall, + maxMessageBytes: number, + onMessage: (message: Uint8Array) => void | Promise, +): GrpcStream { + const received: Received = { body: [], bytes: 0 }; + const stream = session.request({ + ...call.metadata, + ":method": "POST", + ":path": path, + "content-type": "application/grpc", + te: "trailers", + }); + let arrived: Buffer = Buffer.alloc(0), + handling: Promise = Promise.resolve(), + held = 0, + hungUp = false, + failure: unknown; + const fail = (problem: unknown) => { + if (failure !== undefined || hungUp) return; + failure = problem; + clearTimeout(silence); + stream.close(constants.NGHTTP2_CANCEL); + }; + const silence = setTimeout( + () => + fail( + new GrpcFailure( + grpcStatus.DEADLINE_EXCEEDED, + "The sharing service did not answer in time.", + ), + ), + call.timeoutMs ?? DEFAULT_TIMEOUT_MS, + ); + const handOver = (message: Uint8Array) => { + if (++held > HELD_FOR_A_SLOW_READER) stream.pause(); + handling = handling + .then(() => + failure === undefined && !hungUp ? onMessage(message) : undefined, + ) + .then(() => { + if (--held <= HELD_FOR_A_SLOW_READER / 2) stream.resume(); + }, fail); + }; + stream.on("response", (headers) => { + received.headers = headers; + clearTimeout(silence); + }); + stream.on("trailers", (trailers) => (received.trailers = trailers)); + stream.on("data", (part: Buffer) => { + arrived = arrived.length ? Buffer.concat([arrived, part]) : part; + for (;;) { + const next = nextMessage(arrived, maxMessageBytes); + if (!next) return; + if (next instanceof GrpcFailure) return fail(next); + arrived = next.rest; + handOver(next.message); + } + }); + stream.on("error", (error) => fail(notReached(error))); + const finished = new Promise((resolve, reject) => { + stream.on("close", () => { + clearTimeout(silence); + void handling.then(() => { + const ended = hungUp + ? undefined + : (failure ?? endOf(received, arrived)); + if (ended === undefined) resolve(); + else reject(ended); + }); + }); + }); + stream.end(frame(call.request)); + return { + finished, + cancel() { + hungUp = true; + clearTimeout(silence); + stream.close(constants.NGHTTP2_CANCEL); + }, + }; +} + +/** Why a stream that closed did not end well, or nothing when the service ended it properly. */ +function endOf(received: Received, unread: Buffer): GrpcFailure | undefined { + const failure = failureOf(received); + if (failure || !unread.length) return failure; + return new GrpcFailure( + grpcStatus.INTERNAL, + "The sharing service ended in the middle of a message.", + ); +} + +/** After one of these the connection itself is in doubt, so the next call opens another. */ +const connectionInDoubt = (failure: unknown) => + failure instanceof GrpcFailure && + ( + [ + grpcStatus.UNAVAILABLE, + grpcStatus.DEADLINE_EXCEEDED, + grpcStatus.INTERNAL, + grpcStatus.UNKNOWN, + ] as number[] + ).includes(failure.code); + +/** + * gRPC over Node's own HTTP/2: `http://` is unencrypted HTTP/2, `https://` is TLS. + * One connection is opened when first needed and kept while it is in use. + */ +export function grpcChannel( + address: URL, + options: GrpcChannelOptions = {}, +): GrpcChannel { + const pathPrefix = address.pathname.replace(/\/+$/, ""); + const idleMs = options.idleMs ?? DEFAULT_IDLE_MS, + maxReplyBytes = options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES, + keepAliveMs = options.keepAliveMs ?? DEFAULT_KEEP_ALIVE_MS; + let session: ClientHttp2Session | undefined, + idle: ReturnType | undefined, + callsInFlight = 0, + closed = false; + const retire = (retired: ClientHttp2Session) => { + if (session === retired) session = undefined; + }; + const connected = (): ClientHttp2Session => { + if (session && !session.closed && !session.destroyed) return session; + const opened = connect(address.origin); + // Each call reports what went wrong with it; the connection only steps aside. + opened.on("error", () => retire(opened)); + opened.on("goaway", () => retire(opened)); + opened.on("close", () => retire(opened)); + session = opened; + return opened; + }; + /** Asks a connection that carries a stream whether it is still there, and drops one that is not. */ + const keptAlive = (carrying: ClientHttp2Session) => { + const asking = setInterval(() => { + const gaveUp = setTimeout( + () => carrying.destroy(), + KEEP_ALIVE_PATIENCE_MS, + ); + gaveUp.unref(); + const asked = carrying.ping((unanswered) => { + clearTimeout(gaveUp); + if (unanswered) carrying.destroy(); + }); + if (!asked) clearTimeout(gaveUp); + }, keepAliveMs); + asking.unref(); + return () => clearInterval(asking); + }; + const restWhenUnused = () => { + if (--callsInFlight > 0 || !session) return; + const resting = session; + idle = setTimeout(() => { + retire(resting); + resting.close(); + }, idleMs); + idle.unref(); + }; + return { + async unary(call) { + if (closed) + throw new GrpcFailure( + grpcStatus.CANCELLED, + "Sharing was closed before the call was made.", + ); + clearTimeout(idle); + callsInFlight++; + let using: ClientHttp2Session | undefined; + try { + using = connected(); + return await exchange( + using, + pathPrefix + call.path, + call, + maxReplyBytes, + ); + } catch (failure) { + if (using && connectionInDoubt(failure)) { + retire(using); + using.close(); + } + throw failure instanceof GrpcFailure ? failure : notReached(failure); + } finally { + restWhenUnused(); + } + }, + serverStream(call, onMessage) { + if (closed) + return { + finished: Promise.reject( + new GrpcFailure( + grpcStatus.CANCELLED, + "Sharing was closed before the call was made.", + ), + ), + cancel() {}, + }; + clearTimeout(idle); + callsInFlight++; + let using: ClientHttp2Session; + try { + using = connected(); + } catch (failure) { + restWhenUnused(); + return { finished: Promise.reject(notReached(failure)), cancel() {} }; + } + const stream = follow( + using, + pathPrefix + call.path, + call, + maxReplyBytes, + onMessage, + ); + const stopAsking = keptAlive(using); + const finished = stream.finished + .catch((failure) => { + if (connectionInDoubt(failure)) { + retire(using); + using.close(); + } + throw failure; + }) + .finally(() => { + stopAsking(); + restWhenUnused(); + }); + return { finished, cancel: stream.cancel }; + }, + close() { + closed = true; + clearTimeout(idle); + session?.close(); + session = undefined; + }, + }; +} diff --git a/runtime/sharing/memsync/projects-api.ts b/runtime/sharing/memsync/projects-api.ts new file mode 100644 index 0000000..566196a --- /dev/null +++ b/runtime/sharing/memsync/projects-api.ts @@ -0,0 +1,157 @@ +import { WireError, type WireMessage } from "./wire"; +import { + projectsCalls, + projectsContract, + projectsService, + type ProjectsCall, +} from "./projects-contract"; +import { SignedCalls, type ServiceCall } from "./signed-calls"; + +export interface PersonRecord { + accountId: string; + name: string; + /** Their verified address, when they have one. */ + email?: string; +} +export interface InvitationRecord { + id: string; + projectId: string; + projectName: string; + email: string; + /** Missing once the person who invited is no longer on the project. */ + invitedBy?: PersonRecord; + sentAt: string; + expiresAt: string; +} +export interface ProjectRecord { + id: string; + name: string; + owner: PersonRecord; + guests: PersonRecord[]; + openInvitations: InvitationRecord[]; + guestLimit: number; +} + +/** The sharing service's Projects API, as far as MemCode uses it. */ +export interface ProjectsApi { + listProjects(): Promise; + listInvitations(): Promise; + getProject(projectId: string): Promise; + acceptInvitation( + projectId: string, + invitationId: string, + ): Promise; + /** Starts a shared project owned by the caller. */ + startProject(name: string): Promise; + invitePerson(projectId: string, email: string): Promise; + cancelInvitation( + projectId: string, + invitationId: string, + ): Promise; + removeGuest(projectId: string, accountId: string): Promise; + /** A guest leaves a project. The owner cannot. */ + leaveProject(projectId: string): Promise; +} + +const unreadable = () => + new WireError("A reply lacks something it always holds."); +const isMessage = (value: unknown): value is WireMessage => + !!value && typeof value === "object" && !Array.isArray(value); +const messages = (value: unknown) => (Array.isArray(value) ? value : []); + +function person(sent: unknown): PersonRecord { + if (!isMessage(sent) || !sent.account_id) throw unreadable(); + return { + accountId: String(sent.account_id), + name: String(sent.name), + ...(sent.email ? { email: String(sent.email) } : {}), + }; +} + +function moment(sent: unknown): string { + if (!isMessage(sent)) throw unreadable(); + const at = new Date(Number(sent.seconds) * 1000 + Number(sent.nanos) / 1e6); + if (Number.isNaN(at.getTime())) throw unreadable(); + return at.toISOString(); +} + +function invitation(sent: WireMessage): InvitationRecord { + if (!sent.id || !sent.project_id) throw unreadable(); + return { + id: String(sent.id), + projectId: String(sent.project_id), + projectName: String(sent.project_name), + email: String(sent.email), + ...(sent.invited_by ? { invitedBy: person(sent.invited_by) } : {}), + sentAt: moment(sent.sent_at), + expiresAt: moment(sent.expires_at), + }; +} + +function project(sent: WireMessage): ProjectRecord { + if (!sent.id) throw unreadable(); + return { + id: String(sent.id), + name: String(sent.name), + owner: person(sent.owner), + guests: messages(sent.guests).map(person), + openInvitations: messages(sent.open_invitations).map(invitation), + guestLimit: Number(sent.guest_limit), + }; +} + +const call = (name: ProjectsCall): ServiceCall => ({ + service: projectsService, + name, + contract: projectsContract, + ...projectsCalls[name], +}); + +/** The Projects API over gRPC, signed in with the caller's access token. */ +export class MemsyncProjects implements ProjectsApi { + constructor(private readonly calls: SignedCalls) {} + + listProjects() { + return this.calls.unary(call("ListProjects"), {}, (reply) => + messages(reply.projects).map(project), + ); + } + listInvitations() { + return this.calls.unary(call("ListInvitations"), {}, (reply) => + messages(reply.invitations).map(invitation), + ); + } + getProject(projectId: string) { + return this.calls.unary( + call("GetProject"), + { project_id: projectId }, + project, + ); + } + acceptInvitation(projectId: string, invitationId: string) { + const request = { project_id: projectId, invitation_id: invitationId }; + return this.calls.unary(call("AcceptInvitation"), request, project); + } + startProject(name: string) { + return this.calls.unary(call("StartProject"), { name }, project); + } + invitePerson(projectId: string, email: string) { + const request = { project_id: projectId, email }; + return this.calls.unary(call("InvitePerson"), request, invitation); + } + cancelInvitation(projectId: string, invitationId: string) { + const request = { project_id: projectId, invitation_id: invitationId }; + return this.calls.unary(call("CancelInvitation"), request, project); + } + removeGuest(projectId: string, accountId: string) { + const request = { project_id: projectId, account_id: accountId }; + return this.calls.unary(call("RemoveGuest"), request, project); + } + async leaveProject(projectId: string) { + await this.calls.unary( + call("LeaveProject"), + { project_id: projectId }, + () => undefined, + ); + } +} diff --git a/runtime/sharing/memsync/projects-contract.ts b/runtime/sharing/memsync/projects-contract.ts new file mode 100644 index 0000000..a26986e --- /dev/null +++ b/runtime/sharing/memsync/projects-contract.ts @@ -0,0 +1,75 @@ +import type { Contract } from "./wire"; + +/** + * The part of projects.proto MemCode uses, written out by hand. A test reads + * the .proto file beside this one and fails when the two disagree, so take a + * newer contract by copying the file and following what the test says. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +const one = (number: number, message: string) => + ({ number, kind: { message } }) as const; +const many = (number: number, message: string) => + ({ number, kind: { message }, repeated: true }) as const; +const moment = "google.protobuf.Timestamp"; + +export const projectsService = "memsync.v1.Projects"; + +export const projectsContract = { + [moment]: { + seconds: { number: 1, kind: "int64" }, + nanos: { number: 2, kind: "int32" }, + }, + Person: { account_id: text(1), name: text(2), email: text(3) }, + Project: { + id: text(1), + name: text(2), + owner: one(3, "Person"), + guests: many(4, "Person"), + open_invitations: many(5, "Invitation"), + guest_limit: { number: 6, kind: "uint32" }, + }, + Invitation: { + id: text(1), + project_id: text(2), + project_name: text(3), + email: text(4), + invited_by: one(5, "Person"), + sent_at: one(6, moment), + expires_at: one(7, moment), + }, + ListProjectsRequest: {}, + ListProjectsResponse: { projects: many(1, "Project") }, + GetProjectRequest: { project_id: text(1) }, + ListInvitationsRequest: {}, + ListInvitationsResponse: { invitations: many(1, "Invitation") }, + AcceptInvitationRequest: { project_id: text(1), invitation_id: text(2) }, + StartProjectRequest: { name: text(1) }, + InvitePersonRequest: { project_id: text(1), email: text(2) }, + CancelInvitationRequest: { project_id: text(1), invitation_id: text(2) }, + RemoveGuestRequest: { project_id: text(1), account_id: text(2) }, + LeaveProjectRequest: { project_id: text(1) }, + LeaveProjectResponse: {}, +} satisfies Contract; + +/** The calls MemCode makes. Renaming and deleting a project happen at memtrace.io. */ +export const projectsCalls = { + ListProjects: { + request: "ListProjectsRequest", + reply: "ListProjectsResponse", + }, + ListInvitations: { + request: "ListInvitationsRequest", + reply: "ListInvitationsResponse", + }, + GetProject: { request: "GetProjectRequest", reply: "Project" }, + AcceptInvitation: { request: "AcceptInvitationRequest", reply: "Project" }, + StartProject: { request: "StartProjectRequest", reply: "Project" }, + InvitePerson: { request: "InvitePersonRequest", reply: "Invitation" }, + CancelInvitation: { request: "CancelInvitationRequest", reply: "Project" }, + RemoveGuest: { request: "RemoveGuestRequest", reply: "Project" }, + LeaveProject: { + request: "LeaveProjectRequest", + reply: "LeaveProjectResponse", + }, +} as const; +export type ProjectsCall = keyof typeof projectsCalls; diff --git a/runtime/sharing/memsync/projects.proto b/runtime/sharing/memsync/projects.proto new file mode 100644 index 0000000..7c5316b --- /dev/null +++ b/runtime/sharing/memsync/projects.proto @@ -0,0 +1,122 @@ +syntax = "proto3"; + +package memsync.v1; + +import "google/protobuf/timestamp.proto"; + +// Projects and the people on them. +// +// Every call carries the caller's Memtrace access token as +// `authorization: Bearer `. A call that is turned down returns a gRPC +// status whose `memsync-refusal` metadata names the rule that turned it down, +// so MemCode and memtrace.io can show their own wording for it. +service Projects { + // Starts a personal project owned by the caller. + rpc StartProject(StartProjectRequest) returns (Project); + // Lists the projects the caller owns or is a guest on, by name. + rpc ListProjects(ListProjectsRequest) returns (ListProjectsResponse); + // Shows one project the caller is on. + rpc GetProject(GetProjectRequest) returns (Project); + // Invites a person by email address. Only the owner can invite. + rpc InvitePerson(InvitePersonRequest) returns (Invitation); + // Lists the open invitations sent to the caller's verified email address. + rpc ListInvitations(ListInvitationsRequest) returns (ListInvitationsResponse); + // Makes the caller a guest on the project that invited them. + rpc AcceptInvitation(AcceptInvitationRequest) returns (Project); + // Takes back an invitation nobody has accepted, open or expired. Only the owner can. + rpc CancelInvitation(CancelInvitationRequest) returns (Project); + // Takes a guest off the project. Only the owner can. + rpc RemoveGuest(RemoveGuestRequest) returns (Project); + // Takes the caller off a project they are a guest on. The owner cannot leave. + rpc LeaveProject(LeaveProjectRequest) returns (LeaveProjectResponse); + // Gives the project a new name. Only the owner can. + rpc RenameProject(RenameProjectRequest) returns (Project); + // Deletes the project for everyone on it, at once and for good. Only the owner can. + rpc DeleteProject(DeleteProjectRequest) returns (DeleteProjectResponse); +} + +message Person { + string account_id = 1; + string name = 2; + // Empty until the person has verified an address at memtrace.io. + string email = 3; +} + +message Project { + string id = 1; + string name = 2; + Person owner = 3; + repeated Person guests = 4; + // Invitations that can still be accepted. + repeated Invitation open_invitations = 5; + // How many guests and open invitations the project can hold together. + uint32 guest_limit = 6; +} + +message Invitation { + string id = 1; + string project_id = 2; + string project_name = 3; + string email = 4; + Person invited_by = 5; + google.protobuf.Timestamp sent_at = 6; + google.protobuf.Timestamp expires_at = 7; +} + +message StartProjectRequest { + string name = 1; +} + +message ListProjectsRequest {} + +message ListProjectsResponse { + repeated Project projects = 1; +} + +message GetProjectRequest { + string project_id = 1; +} + +message InvitePersonRequest { + string project_id = 1; + string email = 2; +} + +message ListInvitationsRequest {} + +message ListInvitationsResponse { + repeated Invitation invitations = 1; +} + +message AcceptInvitationRequest { + string project_id = 1; + string invitation_id = 2; +} + +message CancelInvitationRequest { + string project_id = 1; + string invitation_id = 2; +} + +message RemoveGuestRequest { + string project_id = 1; + // The guest's `Person.account_id`. + string account_id = 2; +} + +message LeaveProjectRequest { + string project_id = 1; +} + +message LeaveProjectResponse {} + +message RenameProjectRequest { + string project_id = 1; + string name = 2; +} + +message DeleteProjectRequest { + string project_id = 1; +} + +message DeleteProjectResponse {} diff --git a/runtime/sharing/memsync/signed-calls.ts b/runtime/sharing/memsync/signed-calls.ts new file mode 100644 index 0000000..c154dad --- /dev/null +++ b/runtime/sharing/memsync/signed-calls.ts @@ -0,0 +1,170 @@ +import type { AccessToken } from "../access"; +import { refusalNamed, SharingUnavailable } from "../problems"; +import { + GrpcFailure, + grpcStatus, + type GrpcChannel, + type GrpcStream, +} from "./grpc"; +import { + decodeMessage, + encodeMessage, + WireError, + type Contract, + type WireMessage, +} from "./wire"; + +/** Where access tokens come from, and where one the service refused is handed back. */ +export interface AccessTokens { + current(): Promise; + forget(token: string): void; +} + +/** One call of one of the sharing service's APIs, with the shapes of what travels. */ +export interface ServiceCall { + service: string; + name: string; + contract: Contract; + request: string; + reply: string; +} + +const REFUSAL_HEADER = "memsync-refusal"; + +function unavailable(failure: GrpcFailure): SharingUnavailable { + const serviceAnswered = failure.metadata["grpc-status"] !== undefined; + let sentence = + "The address memtrace.io gave for sharing is not a sharing service. Try again later."; + if (failure.code === grpcStatus.UNAUTHENTICATED) + sentence = + "The sharing service did not accept this sign-in. Try again in a few minutes."; + else if (failure.code === grpcStatus.DEADLINE_EXCEEDED) + sentence = + "The sharing service did not answer in time. Try again in a moment."; + else if (serviceAnswered) + sentence = + "The sharing service is having trouble right now. Try again in a few minutes."; + else if (failure.code === grpcStatus.UNAVAILABLE) + sentence = + "The sharing service could not be reached. Check your connection and try again."; + return new SharingUnavailable(sentence, { cause: failure }); +} + +/** What to tell the person about a call that did not end in a reply. */ +function problemWith(call: ServiceCall, failure: unknown): Error { + if (failure instanceof WireError) + return new SharingUnavailable( + "The sharing service sent a reply MemCode could not read. Updating MemCode may help.", + { cause: failure }, + ); + if (!(failure instanceof GrpcFailure)) return failure as Error; + const rule = failure.metadata[REFUSAL_HEADER]; + const refusal = refusalNamed(rule); + if (refusal) return refusal; + // The log keeps what the sentence leaves out: which call, and the service's own words. + console.error( + `[sharing] ${call.name} failed: status ${failure.code}${rule ? `, rule ${rule}` : ""}: ${failure.message}`, + ); + if (rule) + return new SharingUnavailable( + "The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help.", + { cause: failure }, + ); + return unavailable(failure); +} + +const signInWasRefused = (failure: unknown) => + failure instanceof GrpcFailure && + failure.code === grpcStatus.UNAUTHENTICATED && + !failure.metadata[REFUSAL_HEADER]; + +/** + * Calls to the sharing service made as the signed-in person. A token the service + * refuses is replaced once, because its keys or the token may have just changed. + * What goes wrong comes back as a problem the person can be told about. + */ +export class SignedCalls { + constructor( + private readonly channel: Pick, + private readonly access: AccessTokens, + private readonly timeoutMs?: number, + ) {} + + async unary( + call: ServiceCall, + request: WireMessage, + read: (reply: WireMessage) => Answer, + ): Promise { + const first = await this.attempt(call, request, read); + if ("answer" in first) return first.answer; + const second = await this.attempt(call, request, read); + if ("answer" in second) return second.answer; + throw problemWith(call, second.signInRefused); + } + + /** A call the service keeps answering. Each message is read before it is handed over. */ + stream( + call: ServiceCall, + request: WireMessage, + onMessage: (message: WireMessage) => void | Promise, + ): GrpcStream { + let open: GrpcStream | undefined, + hungUp = false; + const follow = async (isLastTry: boolean): Promise => { + const { token } = await this.access.current(); + if (hungUp) return; + open = this.channel.serverStream( + this.sent(call, request, token), + (bytes) => onMessage(decodeMessage(call.contract, call.reply, bytes)), + ); + try { + await open.finished; + } catch (failure) { + if (signInWasRefused(failure)) this.access.forget(token); + if (signInWasRefused(failure) && !isLastTry) return follow(true); + throw problemWith(call, failure); + } + }; + return { + finished: follow(false), + cancel() { + hungUp = true; + open?.cancel(); + }, + }; + } + + private sent(call: ServiceCall, request: WireMessage, token: string) { + return { + path: `/${call.service}/${call.name}`, + request: encodeMessage(call.contract, call.request, request), + metadata: { authorization: `Bearer ${token}` }, + timeoutMs: this.timeoutMs, + }; + } + + /** One try, from the token to the reply as MemCode's own record. */ + private async attempt( + call: ServiceCall, + request: WireMessage, + read: (reply: WireMessage) => Answer, + ): Promise<{ answer: Answer } | { signInRefused: GrpcFailure }> { + const { token } = await this.access.current(); + try { + const reply = await this.channel.unary(this.sent(call, request, token)); + return { + answer: read(decodeMessage(call.contract, call.reply, reply)), + }; + } catch (failure) { + if (signInWasRefused(failure)) { + this.access.forget(token); + return { signInRefused: failure as GrpcFailure }; + } + const problem = problemWith(call, failure); + // A newly verified address reaches the service only in a new token. + if ("rule" in problem && problem.rule === "email_not_verified") + this.access.forget(token); + throw problem; + } + } +} diff --git a/runtime/sharing/memsync/wire.ts b/runtime/sharing/memsync/wire.ts new file mode 100644 index 0000000..ba27614 --- /dev/null +++ b/runtime/sharing/memsync/wire.ts @@ -0,0 +1,271 @@ +/** + * Protocol Buffers (proto3) on the wire, for the kinds of field the sharing + * service's contract uses. A message is described by its shape, so the shapes + * can be checked against the .proto file in a test. + */ +export type ScalarKind = + "string" | "bytes" | "uint32" | "uint64" | "int32" | "int64"; +/** Only messages are repeated in the contract, so only they can be. */ +export type FieldShape = + | { number: number; kind: ScalarKind } + | { number: number; kind: { message: string }; repeated?: boolean }; +export type MessageShape = Record; +/** Message shapes by name. */ +export type Contract = Record; +export type WireValue = + string | number | Uint8Array | WireMessage | WireMessage[]; +export interface WireMessage { + [field: string]: WireValue | undefined; +} + +/** Bytes that are not the message they were said to be, or a value that cannot be sent. */ +export class WireError extends Error {} + +const VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + FIXED32 = 5; +const WIRE_TYPE_BITS = 3, + LONGEST_VARINT = 10, + TWO_TO_64 = 1n << 64n; +const utf8 = new TextDecoder("utf-8", { fatal: true }); +const ranges = { + uint32: [0, 4294967295], + uint64: [0, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + int64: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], +} as const; +type NumberKind = keyof typeof ranges; +const isNumberKind = (kind: FieldShape["kind"]): kind is NumberKind => + typeof kind === "string" && kind in ranges; +const isRepeated = (field: FieldShape) => + "repeated" in field && !!field.repeated; + +function shapeOf(contract: Contract, name: string): MessageShape { + const shape = contract[name]; + if (!shape) throw new WireError(`No shape is known for ${name}.`); + return shape; +} + +class Writer { + private readonly parts: Uint8Array[] = []; + private varint(value: bigint) { + const bytes: number[] = []; + let rest = value; + do { + const low = Number(rest & 0x7fn); + rest >>= 7n; + bytes.push(rest ? low | 0x80 : low); + } while (rest); + this.parts.push(Uint8Array.from(bytes)); + } + private tag(field: number, wireType: number) { + this.varint(BigInt((field << WIRE_TYPE_BITS) | wireType)); + } + number(field: number, value: number) { + this.tag(field, VARINT); + // A negative number travels as its 64-bit two's complement. + this.varint(value < 0 ? TWO_TO_64 + BigInt(value) : BigInt(value)); + } + bytes(field: number, value: Uint8Array) { + this.tag(field, LENGTH_DELIMITED); + this.varint(BigInt(value.length)); + this.parts.push(value); + } + finish(): Uint8Array { + return new Uint8Array(Buffer.concat(this.parts)); + } +} + +function checkedNumber( + kind: NumberKind, + value: unknown, + field: string, +): number { + const [least, most] = ranges[kind]; + if ( + !Number.isInteger(value) || + (value as number) < least || + (value as number) > most + ) + throw new WireError(`${field} is not a ${kind}.`); + return value as number; +} + +function writeField( + writer: Writer, + contract: Contract, + name: string, + { number, kind }: FieldShape, + value: WireValue, +) { + if (typeof kind !== "string") { + if ( + typeof value !== "object" || + value instanceof Uint8Array || + Array.isArray(value) + ) + throw new WireError(`${name} is not a message.`); + writer.bytes(number, encodeMessage(contract, kind.message, value)); + } else if (isNumberKind(kind)) { + if (checkedNumber(kind, value, name) !== 0) + writer.number(number, value as number); + } else if (kind === "string") { + if (typeof value !== "string") throw new WireError(`${name} is not text.`); + if (value) writer.bytes(number, new TextEncoder().encode(value)); + } else { + if (!(value instanceof Uint8Array)) + throw new WireError(`${name} is not bytes.`); + if (value.length) writer.bytes(number, value); + } +} + +/** Writes a message as the reference implementation does: fields by number, defaults left out. */ +export function encodeMessage( + contract: Contract, + message: string, + value: WireMessage, +): Uint8Array { + const writer = new Writer(); + const fields = Object.entries(shapeOf(contract, message)).sort( + ([, left], [, right]) => left.number - right.number, + ); + for (const [name, shape] of fields) { + const given = value[name]; + if (given === undefined) continue; + if (!isRepeated(shape)) writeField(writer, contract, name, shape, given); + else if (!Array.isArray(given)) + throw new WireError(`${name} is not a list.`); + else + for (const item of given) writeField(writer, contract, name, shape, item); + } + return writer.finish(); +} + +class Reader { + private at = 0; + constructor(private readonly source: Uint8Array) {} + get done() { + return this.at >= this.source.length; + } + varint(): bigint { + let value = 0n; + for (let read = 0; read < LONGEST_VARINT; read++) { + if (this.done) throw new WireError("The message ends inside a number."); + const byte = this.source[this.at++]; + value |= BigInt(byte & 0x7f) << BigInt(7 * read); + if (!(byte & 0x80)) return BigInt.asUintN(64, value); + } + throw new WireError("A number in the message never ends."); + } + take(length: number): Uint8Array { + if (length > this.source.length - this.at) + throw new WireError("The message ends inside a field."); + const taken = this.source.subarray(this.at, this.at + length); + this.at += length; + return taken; + } + delimited(): Uint8Array { + const length = this.varint(); + if (length > BigInt(this.source.length)) + throw new WireError("The message ends inside a field."); + return this.take(Number(length)); + } + skip(wireType: number) { + if (wireType === VARINT) this.varint(); + else if (wireType === FIXED64) this.take(8); + else if (wireType === LENGTH_DELIMITED) this.delimited(); + else if (wireType === FIXED32) this.take(4); + else + throw new WireError( + "The message has a field of a kind proto3 does not have.", + ); + } +} + +function numberRead(kind: NumberKind, raw: bigint, field: string): number { + const value = + kind === "int32" || kind === "int64" ? BigInt.asIntN(64, raw) : raw; + const [least, most] = ranges[kind]; + if (value < BigInt(least) || value > BigInt(most)) + throw new WireError(`${field} is out of range for a ${kind}.`); + return Number(value); +} + +function readField( + reader: Reader, + contract: Contract, + name: string, + { kind }: FieldShape, + wireType: number, +): WireValue { + const expected = isNumberKind(kind) ? VARINT : LENGTH_DELIMITED; + if (wireType !== expected) + throw new WireError(`${name} was sent as another kind of field.`); + if (isNumberKind(kind)) return numberRead(kind, reader.varint(), name); + const bytes = reader.delimited(); + if (typeof kind !== "string") + return decodeMessage(contract, kind.message, bytes); + if (kind === "bytes") return new Uint8Array(bytes); + try { + return utf8.decode(bytes); + } catch { + throw new WireError(`${name} is not text.`); + } +} + +function emptyMessage(shape: MessageShape): WireMessage { + const empty: WireMessage = {}; + for (const [name, field] of Object.entries(shape)) { + const { kind } = field; + if (isRepeated(field)) empty[name] = []; + else if (kind === "string") empty[name] = ""; + else if (kind === "bytes") empty[name] = new Uint8Array(); + else if (isNumberKind(kind)) empty[name] = 0; + } + return empty; +} + +/** + * Reads a message. Fields that were not sent read as empty, a message that was + * not sent is left out, and fields this shape does not know are skipped. + * Throws WireError, and nothing else, for bytes that are not such a message. + */ +export function decodeMessage( + contract: Contract, + message: string, + bytes: Uint8Array, +): WireMessage { + const shape = shapeOf(contract, message); + const byNumber = new Map( + Object.entries(shape).map(([name, field]) => [ + field.number, + { name, field }, + ]), + ); + const read = emptyMessage(shape); + const reader = new Reader(bytes); + while (!reader.done) { + const tag = reader.varint(); + const number = Number(tag >> BigInt(WIRE_TYPE_BITS)), + wireType = Number(tag & 7n); + if (number < 1) + throw new WireError("The message has a field without a number."); + const known = byNumber.get(number); + if (!known) { + reader.skip(wireType); + continue; + } + const value = readField( + reader, + contract, + known.name, + known.field, + wireType, + ); + if (isRepeated(known.field)) + (read[known.name] as WireMessage[]).push(value as WireMessage); + else read[known.name] = value; + } + return read; +} diff --git a/runtime/sharing/problems.ts b/runtime/sharing/problems.ts new file mode 100644 index 0000000..9c857d1 --- /dev/null +++ b/runtime/sharing/problems.ts @@ -0,0 +1,35 @@ +import { + isRefusalRule, + refusalSentences, + type RefusalRule, +} from "../../src/sharing-refusals"; + +/** There is no Memtrace sign-in to show. The person has to sign in. */ +export class SharingSignedOut extends Error { + constructor(message = "Sign in to Memtrace to see the projects you share.") { + super(message); + this.name = "SharingSignedOut"; + } +} + +/** Sharing cannot be used right now. The message says what the person can do. */ +export class SharingUnavailable extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "SharingUnavailable"; + } +} + +/** One of the sharing service's rules turned the request down. The message is MemCode's sentence for it. */ +export class SharingRefused extends Error { + constructor(readonly rule: RefusalRule) { + super(refusalSentences[rule]); + this.name = "SharingRefused"; + } +} + +/** The refusal for a rule name the service sent, or nothing for a name MemCode does not know. */ +export const refusalNamed = (rule: string | undefined) => + rule !== undefined && isRefusalRule(rule) + ? new SharingRefused(rule) + : undefined; diff --git a/runtime/sharing/routes.ts b/runtime/sharing/routes.ts new file mode 100644 index 0000000..dbd8391 --- /dev/null +++ b/runtime/sharing/routes.ts @@ -0,0 +1,86 @@ +import { z } from "zod"; +import type { Sharing } from "./sharing"; + +type Register = ( + method: string, + schema: z.ZodType, + handler: (input: any) => unknown, +) => void; + +const id = z.string().min(1).max(200); + +/** What the app's window may ask of sharing. */ +export function registerSharing(register: Register, sharing: Sharing) { + register("sharing:overview", z.undefined(), () => sharing.overview()); + register( + "sharing:accept-invitation", + z.object({ projectId: id, invitationId: id }).strict(), + (input) => sharing.acceptInvitation(input), + ); + register( + "sharing:connect", + z.object({ projectId: id, sharedProjectId: id }).strict(), + (input) => sharing.connect(input), + ); + register( + "sharing:disconnect", + z.object({ projectId: id }).strict(), + ({ projectId }) => sharing.disconnect(projectId), + ); + const task = z.object({ taskId: id }).strict(); + register("sharing:follow-card", task, ({ taskId }) => + sharing.followCard(taskId), + ); + register("sharing:unfollow-card", task, ({ taskId }) => + sharing.unfollowCard(taskId), + ); + register( + "sharing:share-result", + z.object({ taskId: id, artifactId: id }).strict(), + (input) => sharing.shareResult(input), + ); + register( + "sharing:decide-message", + z.object({ taskId: id, messageId: id, allow: z.boolean() }).strict(), + (input) => sharing.decideMessage(input), + ); + register( + "sharing:open-result", + z.object({ taskId: id, resultId: id }).strict(), + (input) => sharing.openSharedResult(input), + ); + const project = z.object({ projectId: id }).strict(); + register("sharing:share", project, ({ projectId }) => + sharing.shareProject(projectId), + ); + register( + "sharing:invite", + z + .object({ projectId: id, email: z.string().trim().min(3).max(320) }) + .strict(), + (input) => sharing.invite(input), + ); + register( + "sharing:cancel-invitation", + z.object({ projectId: id, invitationId: id }).strict(), + (input) => sharing.cancelInvitation(input), + ); + register( + "sharing:remove-person", + z.object({ projectId: id, personId: id }).strict(), + (input) => sharing.removePerson(input), + ); + register("sharing:leave", project, ({ projectId }) => + sharing.leave(projectId), + ); + register( + "sharing:open", + z.object({ sharedProjectId: id }).strict(), + ({ sharedProjectId }) => sharing.openShared(sharedProjectId), + ); + register( + "sharing:join", + z.object({ sharedProjectId: id, invitationId: id }).strict(), + (input) => sharing.join(input), + ); +} diff --git a/runtime/sharing/sharing.ts b/runtime/sharing/sharing.ts new file mode 100644 index 0000000..6fd7d55 --- /dev/null +++ b/runtime/sharing/sharing.ts @@ -0,0 +1,934 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { basename, join } from "node:path"; +import type { AppState, Artifact, Message, Project } from "../../src/shared"; +import type { WorkerInputResponse } from "../../src/worker-input"; +import type { WorkerChanges } from "../../src/changes"; +import type { StoryReviewRun } from "../../src/code-review"; +import type { + SharingSettings, + PendingInvitation, + SharedPerson, + SharedProject, + SharedProjectLink, + SharingOverview, +} from "../../src/sharing"; +import { twoBoards } from "../../src/sharing-board"; +import type { StoryAuthor } from "../../src/story-comments"; +import type { BetaSessionProof } from "../beta"; +import { SharingAccess } from "./access"; +import { sharingAddresses } from "./addresses"; +import { BoardStore } from "./board/store"; +import { BoardSync } from "./board/sync"; +import { CardActivity } from "./cards/activity"; +import type { WritingDevice } from "./cards/entries"; +import { LARGEST_SHARED_FILE, previewKindOf } from "./cards/files"; +import { within } from "../local"; +import { MemsyncBoards, type BoardsApi } from "./memsync/boards-api"; +import { MemsyncCards, type CardsApi } from "./memsync/cards-api"; +import { LARGEST_CARDS_MESSAGE } from "./memsync/cards-contract"; +import { grpcChannel, type GrpcChannel } from "./memsync/grpc"; +import { + MemsyncProjects, + type InvitationRecord, + type PersonRecord, + type ProjectRecord, + type ProjectsApi, +} from "./memsync/projects-api"; +import { SignedCalls } from "./memsync/signed-calls"; +import { + SharingRefused, + SharingSignedOut, + SharingUnavailable, +} from "./problems"; + +export interface SharingOptions { + state(): AppState; + /** Saves the workspace and tells the app's window. */ + changed(): Promise; + /** The Memtrace sign-in to show memtrace.io. Null: nobody is signed in. */ + session(): Promise; + /** Where the sharing service is, as memtrace.io lists it. Nothing: sharing is not offered. */ + addresses(): Promise; + /** Makes an empty project on this computer for a shared board, and opens it. */ + makeProject?(name: string): Promise; + /** Where each connected board keeps what it needs between runs. */ + boardsFolder: string; + /** + * Saves the workspace as it is at the moment of the call, and writes it only + * after `first` has finished. Board sync saves its own state through `first`. + */ + saveWorkspace(first: () => Promise): Promise; + /** What the window shows changed, and nothing needs saving. */ + shown?(): void; + /** What sharing a card's activity needs of this computer. Without it, no file can be shared. */ + cards?: CardHost; + fetcher?: typeof fetch; + now?: () => string; +} + +/** Everything that talks to one sharing service, built from one pair of addresses. */ +interface Service { + settingsKey: string; + address: string; + channel: GrpcChannel; + access: SharingAccess; + projects: ProjectsApi; + boards: BoardsApi; + cards: CardsApi; +} +export interface CardHost { + /** The latest code review report of a task on this computer. */ + reviewOf(taskId: string): Promise; + /** A file a task saved, when it may be shared. Throws a sentence when it may not. */ + shareableFile( + taskId: string, + artifactId: string, + ): Promise<{ + name: string; + mime: string; + kind: "report" | "artifact"; + bytes: Uint8Array; + }>; + /** What a task changed, as the Changes tab shows it. */ + changesOf(taskId: string): Promise; + /** Where a file shared from a card is kept on this computer: a folder its previews may read. */ + filesFolder(taskId: string): string; + /** Continues a worker run here with a follow-up sent from another computer. */ + continueWorker?(taskId: string, message: Message): Promise; + /** Answers what a worker run here waits for, with an answer sent from another computer. */ + answerWorker?( + taskId: string, + inputId: string, + response: WorkerInputResponse, + ): Promise; +} +/** Board sync running for one connected project. */ +interface RunningBoard { + link: SharedProjectLink; + service: Service; + sync: BoardSync; + cards: CardActivity; +} + +/** A card's activity is written at most this often while a worker runs. */ +const CARDS_EVERY_MS = 1000; +const platformName = (): WritingDevice["name"] => + process.platform === "win32" + ? "Windows" + : process.platform === "darwin" + ? "Mac" + : "Linux"; +/** How long connecting waits for board sync to say how the two boards stand. */ +const FIRST_WORD_MS = 8000; +const NOT_OFFERED = "Sharing is not available right now. Try again later."; + +const shownPerson = ( + person: PersonRecord, + accountId: string, +): SharedPerson => ({ + id: person.accountId, + name: person.name, + isYou: person.accountId === accountId, +}); +function shownProject( + project: ProjectRecord, + accountId: string, +): SharedProject { + const youAreOwner = project.owner.accountId === accountId; + return { + id: project.id, + name: project.name, + owner: shownPerson(project.owner, accountId), + guests: project.guests.map((guest) => shownPerson(guest, accountId)), + youAreOwner, + // Only the owner, who sent them, sees whom the invitations are for. + openInvitations: project.openInvitations.map((invitation) => ({ + id: invitation.id, + email: youAreOwner ? invitation.email : "", + sentAt: invitation.sentAt, + })), + guestLimit: project.guestLimit, + }; +} +const shownInvitation = (invitation: InvitationRecord): PendingInvitation => ({ + id: invitation.id, + projectId: invitation.projectId, + projectName: invitation.projectName, + invitedBy: invitation.invitedBy?.name ?? "The project's owner", + expiresAt: invitation.expiresAt, +}); + +/** A folder name for a link that no other link on this computer gets. */ +const folderOf = (link: SharedProjectLink) => + createHash("sha256") + .update([link.service, link.sharedProjectId, link.projectId].join("\n")) + .digest("hex") + .slice(0, 32); + +/** + * Sharing a project through the sharing service: who is signed in, the shared + * projects and invitations of that person, which shared project each local + * project is connected to, and the board sync that runs for each of those. + */ +export class Sharing { + private service?: Service; + private readonly boards = new Map(); + private matching: Promise = Promise.resolve(); + private device?: Promise; + private cardsTimer?: NodeJS.Timeout; + private cardsLookedAt = 0; + private readonly changes = new Map(); + private readonly now: () => string; + constructor(private readonly options: SharingOptions) { + this.now = options.now ?? (() => new Date().toISOString()); + // The workspace file may hold how boards stood when MemCode last ran, + // and what cards showed from other computers. Both are read again. + const state = options.state(); + state.sharedBoards = []; + // Addresses typed in Settings by an earlier build: MemCode now finds the service itself. + delete (state.settings as { sharing?: unknown }).sharing; + for (const task of state.tasks) + if ( + task.sharedFromLog || + task.sharedResults || + task.sharedInputs || + task.sharedAsks + ) { + delete task.sharedSession; + delete task.sharedFromLog; + delete task.sharedResults; + delete task.sharedRunIsYours; + delete task.sharedInputs; + delete task.sharedAsks; + } + } + + /** What the Share panel and the switcher show. A problem is part of the answer, with what to do about it. */ + async overview(): Promise { + try { + const service = await this.serviceInUse(); + if (!service) return { state: "not-set" }; + const [{ accountId }, projects, invitations] = await Promise.all([ + service.access.current(), + service.projects.listProjects(), + service.projects.listInvitations(), + ]); + return { + state: "ready", + accountId, + service: service.address, + projects: projects.map((project) => shownProject(project, accountId)), + invitations: invitations.map(shownInvitation), + }; + } catch (problem) { + if (problem instanceof SharingSignedOut) + return { state: "signed-out", detail: problem.message }; + if ( + problem instanceof SharingUnavailable || + problem instanceof SharingRefused + ) + return { state: "unavailable", detail: problem.message }; + throw problem; + } + } + + async acceptInvitation(input: { + projectId: string; + invitationId: string; + }): Promise { + await ( + await this.requiredService() + ).projects.acceptInvitation(input.projectId, input.invitationId); + return this.overview(); + } + + // ── Sharing a project from inside MemCode ───────────────────────────────── + + /** + * Shares a project on this computer: the first time, a shared project of + * the same name is started for it and its board is written there. After + * that, it answers the link it has. + */ + async shareProject(projectId: string): Promise { + const service = await this.requiredService(); + const known = this.linkOf(projectId, service); + if (known) return known; + const state = this.options.state(); + const local = state.projects.find((project) => project.id === projectId); + if (!local) throw new Error("Project not found."); + assertMayBeShared(local, state); + const started = await service.projects.startProject(local.name); + return this.connect({ projectId, sharedProjectId: started.id }); + } + + /** Invites someone by email, sharing the project first if it is not shared yet. */ + async invite(input: { projectId: string; email: string }) { + const link = await this.shareProject(input.projectId); + const service = await this.requiredService(); + await service.projects.invitePerson( + link.sharedProjectId, + input.email.trim(), + ); + return this.overview(); + } + + async cancelInvitation(input: { projectId: string; invitationId: string }) { + const { service, link } = await this.linkedProject(input.projectId); + await service.projects.cancelInvitation( + link.sharedProjectId, + input.invitationId, + ); + return this.overview(); + } + + async removePerson(input: { projectId: string; personId: string }) { + const { service, link } = await this.linkedProject(input.projectId); + await service.projects.removeGuest(link.sharedProjectId, input.personId); + return this.overview(); + } + + /** A guest leaves a shared project. The board stays on this computer, no longer shared. */ + async leave(projectId: string) { + const { service, link } = await this.linkedProject(projectId); + await service.projects.leaveProject(link.sharedProjectId); + await this.disconnect(projectId); + return this.overview(); + } + + /** + * Opens a shared project on this computer: the project that already holds + * its board, or a new, empty one that takes the board from the log. + */ + async openShared(sharedProjectId: string): Promise<{ projectId: string }> { + const service = await this.requiredService(); + const state = this.options.state(); + const here = (state.sharedProjectLinks ?? []).find( + (link) => + link.sharedProjectId === sharedProjectId && + link.service === service.address && + state.projects.some((project) => project.id === link.projectId), + ); + if (here) { + state.activeProjectId = here.projectId; + await this.options.changed(); + return { projectId: here.projectId }; + } + if (!this.options.makeProject) + throw new Error("A shared project cannot be opened in this MemCode."); + const shared = await service.projects.getProject(sharedProjectId); + const made = await this.options.makeProject(shared.name); + try { + await this.connect({ projectId: made.id, sharedProjectId: shared.id }); + } catch (problem) { + // Nothing was on the new project. It goes, and the reason is said. + state.projects = state.projects.filter( + (project) => project.id !== made.id, + ); + await this.options.changed(); + throw problem; + } + return { projectId: made.id }; + } + + /** Accepts an invitation and opens the shared project on this computer. */ + async join(input: { sharedProjectId: string; invitationId: string }) { + await ( + await this.requiredService() + ).projects.acceptInvitation(input.sharedProjectId, input.invitationId); + return this.openShared(input.sharedProjectId); + } + + private linkOf(projectId: string, service: Service) { + return this.options + .state() + .sharedProjectLinks?.find( + (link) => + link.projectId === projectId && link.service === service.address, + ); + } + + private async linkedProject(projectId: string) { + const service = await this.requiredService(); + const link = this.linkOf(projectId, service); + if (!link) throw new Error("This project is not shared."); + return { service, link }; + } + + /** Records that a local project's board belongs to a shared project the person is on. */ + async connect(input: { + projectId: string; + sharedProjectId: string; + }): Promise { + const service = await this.requiredService(); + const local = this.assertFree(input, service); + const [{ accountId }, shared] = await Promise.all([ + service.access.current(), + service.projects.getProject(input.sharedProjectId), + ]); + const link: SharedProjectLink = { + projectId: input.projectId, + sharedProjectId: shared.id, + sharedProjectName: shared.name, + accountId, + service: service.address, + connectedAt: this.now(), + }; + // Whatever an earlier connection left behind belongs to another moment of this board. + await new BoardStore(this.boardFolder(link)).remove(); + // Another connect may have finished while the service was being asked. + this.assertFree(input, service); + (this.options.state().sharedProjectLinks ??= []).push(link); + await this.options.changed(); + await this.syncBoards(); + // Both boards have work on them: they stay two, and the project is not connected. + if ((await this.firstWordOn(link.projectId)) === "apart") { + await this.disconnect(link.projectId); + throw new Error(twoBoards({ local: local.name, shared: shared.name })); + } + return link; + } + + /** + * How a board that just started stands once it has read the log, or + * `starting` when the service takes longer than a person should wait. + */ + private async firstWordOn(projectId: string) { + const patience = Date.now() + FIRST_WORD_MS; + for (;;) { + const state = this.boards.get(projectId)?.sync.status().state; + if (state !== "starting" || Date.now() > patience) return state; + await new Promise((resolve) => setTimeout(resolve, 25)); + } + } + + /** Forgets the link on this computer. The person stays on the shared project. */ + async disconnect(projectId: string): Promise { + const state = this.options.state(); + const kept = (state.sharedProjectLinks ?? []).filter( + (link) => link.projectId !== projectId, + ); + if (kept.length === (state.sharedProjectLinks ?? []).length) return; + const running = this.boards.get(projectId); + this.boards.delete(projectId); + await running?.sync.stop(); + await running?.cards.stop(); + for (const link of state.sharedProjectLinks ?? []) + if (link.projectId === projectId) + await new BoardStore(this.boardFolder(link)).remove(); + state.sharedProjectLinks = kept; + this.showBoards(); + await this.options.changed(); + } + + /** + * Makes board sync run for exactly the projects the signed-in person has + * connected to the sharing service in use. For when MemCode starts, and when + * the sign-in, the addresses or the links change. + */ + syncBoards(): Promise { + const matched = this.matching.then(() => this.matchBoardsToLinks()); + this.matching = matched.catch((problem) => + console.error("Board sync could not be started:", problem), + ); + return this.matching; + } + + /** The workspace was saved. Changes made on this computer to connected boards are found now. */ + async workspaceSaved(): Promise { + this.workerActivity(); + const projects = this.options.state().projects; + await Promise.all( + [...this.boards.values()].map(({ link, sync }) => + projects.some((project) => project.id === link.projectId) + ? sync + .capture() + .catch((problem) => + console.error("A board change was not picked up:", problem), + ) + : undefined, + ), + ); + } + + /** Who a comment written in a connected project is by: the person signed in to Memtrace. */ + author(projectId: string): StoryAuthor | undefined { + const running = this.boards.get(projectId); + if (!running) return undefined; + const { accountId } = running.link; + return { + id: accountId, + name: running.sync.nameOf(accountId) ?? "You", + source: "memtrace", + }; + } + + async close(): Promise { + clearTimeout(this.cardsTimer); + await this.matching; + const running = [...this.boards.values()]; + this.boards.clear(); + await Promise.all( + running.map(({ sync, cards }) => + Promise.all([sync.stop(), cards.stop()]), + ), + ); + this.closeService(); + } + + // ── What happens on a card ─────────────────────────────────────────────── + + /** + * A worker did something, or the workspace was saved: what changed in a run + * on this computer is written to its card's log, at most once a second. + */ + workerActivity(): void { + if (this.cardsTimer) return; + const wait = Math.max(0, this.cardsLookedAt + CARDS_EVERY_MS - Date.now()); + this.cardsTimer = setTimeout(() => { + this.cardsTimer = undefined; + this.cardsLookedAt = Date.now(); + void this.captureCards(); + }, wait); + this.cardsTimer.unref?.(); + } + + /** Writes what changed in every run on this computer, now. */ + async captureCards(): Promise { + await Promise.all( + [...this.boards.values()].map(({ cards }) => + cards + .capture() + .catch((problem) => + console.error("A card's activity was not written:", problem), + ), + ), + ); + } + + /** A card was opened: its activity on other computers is read and followed. */ + followCard(taskId: string): void { + this.boardOfTask(taskId)?.cards.follow(taskId); + } + unfollowCard(taskId: string): void { + this.boardOfTask(taskId)?.cards.unfollow(taskId); + } + + /** Whether a card shows a worker run from another computer. What is sent to it goes through the card's log. */ + showsRunElsewhere(taskId: string): boolean { + return !!this.taskNamed(taskId)?.sharedFromLog; + } + + /** Sends a follow-up to the worker a card shows from another computer. Its id is the message's. */ + messageWorker(taskId: string, text: string): Promise { + return this.requiredBoardOfTask(taskId).cards.messageWorker(taskId, text); + } + + /** Answers what the worker a card shows from another computer waits for. */ + async answerWorker( + taskId: string, + inputId: string, + response: WorkerInputResponse, + ): Promise { + await this.requiredBoardOfTask(taskId).cards.answerWorker( + taskId, + inputId, + response, + ); + } + + /** Allows or declines a message someone else sent to a worker run here. */ + decideMessage(input: { + taskId: string; + messageId: string; + allow: boolean; + }): Promise { + return this.requiredBoardOfTask(input.taskId).cards.decide( + input.taskId, + input.messageId, + input.allow, + ); + } + + /** Shares a file a task saved with everyone on the shared project. */ + async shareResult(input: { taskId: string; artifactId: string }) { + const running = this.requiredBoardOfTask(input.taskId); + const file = await this.cardHost().shareableFile( + input.taskId, + input.artifactId, + ); + const result = await running.cards.shareResult(input.taskId, file); + return { id: result.id, name: result.name }; + } + + /** Fetches a file shared from a card and keeps it beside the card, to open like its own. */ + async openSharedResult(input: { + taskId: string; + resultId: string; + }): Promise { + const running = this.requiredBoardOfTask(input.taskId); + const task = this.taskNamed(input.taskId)!; + const result = task.sharedResults?.find( + (item) => item.id === input.resultId, + ); + if (!result) throw new Error("That shared file is no longer on this card."); + const content = await this.fetchShared(running, result.sha256, result.size); + const folder = this.cardHost().filesFolder(task.id); + const safeName = + basename(result.name) + .replace(/[<>:"/\\|?*\x00-\x1f]/g, "_") + .slice(0, 160) || "shared-file"; + const path = join( + folder, + `shared-${createHash("sha256").update(result.id).digest("hex").slice(0, 20)}-${safeName}`, + ); + if (!within(folder, path)) + throw new Error("That shared file has an unusable name."); + await mkdir(folder, { recursive: true }); + await writeFile(path, content); + const artifact: Artifact = { + id: `shared:${result.id}`, + projectId: task.projectId, + taskId: task.id, + name: result.name, + kind: previewKindOf(result.mime), + path, + createdAt: result.sharedAt, + source: result.sharedBy, + purpose: result.kind === "report" ? "report" : "deliverable", + revision: result.sha256, + }; + const state = this.options.state(); + state.artifacts = [ + ...state.artifacts.filter((item) => item.id !== artifact.id), + artifact, + ]; + await this.options.changed(); + return artifact; + } + + /** The changes last shared from a card whose run is shown from another computer. */ + async sharedChanges(taskId: string): Promise { + const running = this.boardOfTask(taskId); + const task = this.taskNamed(taskId); + const latest = task?.sharedResults + ?.filter((result) => result.kind === "patch") + .sort((left, right) => left.sharedAt.localeCompare(right.sharedAt)) + .at(-1); + if (!running || !task || !latest) return undefined; + const known = this.changes.get(latest.sha256); + if (known) return { ...known, taskId }; + const content = await this.fetchShared(running, latest.sha256, latest.size); + let read: WorkerChanges; + try { + read = JSON.parse( + new TextDecoder("utf-8", { fatal: true }).decode(content), + ); + } catch { + throw new Error("The changes shared from this card could not be read."); + } + if (!isChanges(read)) + throw new Error("The changes shared from this card could not be read."); + this.changes.set(latest.sha256, read); + return { ...read, taskId }; + } + + private async fetchShared( + running: RunningBoard, + sha256: string, + size: number, + ): Promise { + const { content } = await running.service.cards.download( + running.link.sharedProjectId, + sha256, + ); + if ( + content.length !== size || + createHash("sha256").update(content).digest("hex") !== sha256 + ) + throw new Error("That shared file did not arrive whole. Try again."); + return content; + } + + private taskNamed(taskId: string) { + return this.options.state().tasks.find((task) => task.id === taskId); + } + + private boardOfTask(taskId: string): RunningBoard | undefined { + const task = this.taskNamed(taskId); + return task ? this.boards.get(task.projectId) : undefined; + } + + private requiredBoardOfTask(taskId: string): RunningBoard { + const running = this.boardOfTask(taskId); + if (!running) throw new Error("This card's project is not being shared."); + return running; + } + + private cardHost(): CardHost { + if (!this.options.cards) + throw new Error("Files cannot be shared from this MemCode."); + return this.options.cards; + } + + /** This computer, as card logs name it: an id of its own and its kind. */ + private thisComputer(): Promise { + this.device ??= (async () => { + const path = join(this.options.boardsFolder, "computer.json"); + try { + const kept = JSON.parse(await readFile(path, "utf8")); + if (typeof kept.id === "string" && /^[0-9a-f-]{36}$/.test(kept.id)) + return { id: kept.id, name: platformName() }; + } catch { + // None yet. + } + const made = { id: randomUUID(), name: platformName() }; + await mkdir(this.options.boardsFolder, { recursive: true }); + await writeFile(path, JSON.stringify({ id: made.id }), "utf8"); + return made; + })(); + return this.device; + } + + private closeService() { + this.service?.channel.close(); + this.service = undefined; + } + + private boardFolder(link: SharedProjectLink) { + return join(this.options.boardsFolder, folderOf(link)); + } + + private async matchBoardsToLinks(): Promise { + const state = this.options.state(); + let service: Service | null = null; + // No shared project on this computer: the service is not even looked for. + if (state.sharedProjectLinks?.length) + try { + service = await this.serviceInUse(); + } catch { + // An address that cannot be used: nothing is synchronized. + } + const session = service + ? await this.options.session().catch(() => null) + : null; + const wanted = (state.sharedProjectLinks ?? []).filter( + (link) => + link.service === service?.address && + link.accountId === session?.accountId && + state.projects.some( + (project) => project.id === link.projectId && !project.example, + ), + ); + for (const [projectId, running] of this.boards) { + const stays = wanted.some( + (link) => + link.projectId === projectId && + link.sharedProjectId === running.link.sharedProjectId && + running.service === service, + ); + if (stays) continue; + this.boards.delete(projectId); + await running.sync.stop(); + await running.cards.stop(); + } + const device = wanted.length ? await this.thisComputer() : undefined; + for (const link of wanted) + if (!this.boards.has(link.projectId)) + this.startBoard(link, service!, device!); + this.showBoards(); + } + + private startBoard( + link: SharedProjectLink, + service: Service, + device: WritingDevice, + ): void { + const sync = new BoardSync({ + projectId: link.projectId, + sharedProjectId: link.sharedProjectId, + folder: this.boardFolder(link), + state: this.options.state, + boards: service.boards, + saveWorkspace: this.options.saveWorkspace, + shown: () => this.showBoards(), + people: async () => { + const shared = await service.projects.getProject(link.sharedProjectId); + return new Map( + [shared.owner, ...shared.guests].map((person) => [ + person.accountId, + person.name, + ]), + ); + }, + }); + const cards = new CardActivity({ + projectId: link.projectId, + sharedProjectId: link.sharedProjectId, + device, + folder: this.boardFolder(link), + state: this.options.state, + cards: service.cards, + reviewOf: (taskId) => + this.options.cards?.reviewOf(taskId) ?? Promise.resolve(null), + changesOf: async (taskId) => { + const changes = await this.cardHost().changesOf(taskId); + if (!changes.checkpoints.length) return undefined; + return new TextEncoder().encode(JSON.stringify(changes)); + }, + savedFileOf: (taskId, artifactId) => + this.cardHost().shareableFile(taskId, artifactId), + nameOf: (account) => sync.nameOf(account), + learnName: (account) => sync.learnName(account), + shown: () => this.options.shown?.(), + me: link.accountId, + deliver: (taskId, message) => + this.cardHost().continueWorker?.(taskId, message) ?? + Promise.reject(new Error("Workers cannot be continued from here.")), + answer: (taskId, inputId, response) => + this.cardHost().answerWorker?.(taskId, inputId, response) ?? + Promise.reject(new Error("Workers cannot be answered from here.")), + }); + this.boards.set(link.projectId, { link, service, sync, cards }); + sync.start(); + // Messages sent to workers here while MemCode was closed are read now. + void cards + .capture() + .catch((problem) => + console.error("Card activity could not start:", problem), + ); + } + + /** Puts how each board stands where the window reads it. */ + private showBoards(): void { + this.options.state().sharedBoards = [...this.boards.values()].map( + ({ sync }) => sync.status(), + ); + this.options.shown?.(); + } + + private assertFree( + input: { projectId: string; sharedProjectId: string }, + service: Service, + ) { + const state = this.options.state(); + const local = state.projects.find( + (project) => project.id === input.projectId, + ); + if (!local) throw new Error("Project not found."); + assertMayBeShared(local, state); + const links = state.sharedProjectLinks ?? []; + const existing = links.find((link) => link.projectId === local.id); + if (existing) + throw new Error( + `This project is already connected to “${existing.sharedProjectName}”. Disconnect it first.`, + ); + const taken = links.find( + (link) => + link.sharedProjectId === input.sharedProjectId && + link.service === service.address, + ); + const takenBy = + taken && state.projects.find((project) => project.id === taken.projectId); + if (taken && takenBy) + throw new Error( + `“${taken.sharedProjectName}” is already connected to “${takenBy.name}” on this computer.`, + ); + return local; + } + + private async requiredService(): Promise { + const service = await this.serviceInUse(); + if (!service) throw new Error(NOT_OFFERED); + return service; + } + + /** The service at the addresses memtrace.io lists now. Changed addresses start a new one. */ + private async serviceInUse(): Promise { + const settings = await this.options.addresses(); + const settingsKey = JSON.stringify([ + settings?.memsyncUrl ?? "", + settings?.tokenUrl ?? "", + ]); + if (this.service?.settingsKey === settingsKey) return this.service; + this.closeService(); + let addresses: ReturnType; + try { + addresses = sharingAddresses(settings); + } catch (mistyped) { + throw new SharingUnavailable((mistyped as Error).message); + } + if (!addresses) return null; + const { memsync, tokenEndpoint } = addresses; + // A file from a card comes back in one reply of up to 6 MiB. + const channel = grpcChannel(memsync, { + maxReplyBytes: LARGEST_CARDS_MESSAGE, + }); + const access = new SharingAccess({ + session: this.options.session, + tokenEndpoint: () => tokenEndpoint, + fetcher: this.options.fetcher, + }); + const calls = new SignedCalls(channel, access); + this.service = { + settingsKey, + address: memsync.href, + channel, + access, + projects: new MemsyncProjects(calls), + boards: new MemsyncBoards(calls), + // A whole file goes in one call, so a call is given longer. + cards: new MemsyncCards(new SignedCalls(channel, access, 60_000)), + }; + return this.service; + } +} + +function assertMayBeShared(local: Project, state: AppState) { + if (local.example) + throw new Error( + "The example project cannot be connected. Open one of your own projects first.", + ); + // Team Sync keeps its own copy of this board in step. Two services must not both do that. + if (state.team?.some((room) => room.projectId === local.id)) + throw new Error( + "This project is shared through Team Sync. Leave its team before connecting it to a shared project.", + ); +} + +/** Whether what was read has the shape of a task's changes. */ +function isChanges(value: unknown): value is WorkerChanges { + const read = value as WorkerChanges | null; + return ( + !!read && + typeof read === "object" && + Array.isArray(read.checkpoints) && + read.checkpoints.length <= 1000 && + read.checkpoints.every( + (checkpoint) => + !!checkpoint && + typeof checkpoint.id === "string" && + Array.isArray(checkpoint.files) && + checkpoint.files.every( + (file) => + !!file && + typeof file.path === "string" && + Array.isArray(file.hunks) && + file.hunks.every( + (hunk) => + !!hunk && + Array.isArray(hunk.lines) && + hunk.lines.every( + (line) => + !!line && + typeof line.text === "string" && + ["context", "add", "delete"].includes(line.kind), + ), + ), + ), + ) && + typeof read.additions === "number" && + typeof read.deletions === "number" && + typeof read.files === "number" + ); +} diff --git a/runtime/worker-connections.ts b/runtime/worker-connections.ts index 96e97b0..203c82f 100644 --- a/runtime/worker-connections.ts +++ b/runtime/worker-connections.ts @@ -14,6 +14,7 @@ import { probeStandardCatalog, type StandardHarness, } from "./agents/standard-acp"; +import { inspectDshProfiles } from "./dsh-profiles"; import type { NativeHost } from "./host"; import { harnessNames, @@ -68,20 +69,53 @@ type WorkerReadiness = Pick< async function probeStandardConnection( harness: StandardHarness, command: Command, -): Promise { + dshProfile?: string, +): Promise<{ readiness: WorkerReadiness; note?: string }> { + let profile: string | undefined; + if (harness === "dsh") { + let info; + try { + info = await inspectDshProfiles(dshProfile); + } catch { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: "The configured DeepSeek Harness profile name is invalid. Choose or create an ACP profile in DeepSeek Harness setup.", + }; + } + profile = info.activeProfile; + if (info.activeProfileIssue === "non-acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `DeepSeek Harness profile "${profile}" is not an ACP profile. Choose or create an ACP profile in DeepSeek Harness setup.`, + }; + } + if (info.activeProfileIssue === "missing" && profile !== "acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `DeepSeek Harness profile "${profile}" does not exist. Choose or create an ACP profile in DeepSeek Harness setup.`, + }; + } + } try { - const models = await probeStandardCatalog(harness, command); + const models = await probeStandardCatalog(harness, command, profile); // The CLI confirms provider access at the first model call. - if (models.length) return { auth: "provider-managed" }; + if (models.length) return { readiness: { auth: "provider-managed" } }; } catch (error) { if ( harness === "dsh" && + profile === "acp" && error instanceof Error && /profile ["']acp["'] does not exist/i.test(clean(error.message)) ) - return { auth: "unknown", connectionIssue: "unsupported-cli" }; + return { readiness: { auth: "unknown", connectionIssue: "unsupported-cli" } }; + if (harness === "dsh" && profile && profile !== "acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `MemCode couldn’t read the model list from DeepSeek Harness profile "${profile}". Check the profile setup and providers, then try again.`, + }; + } } - return { auth: "unknown", connectionIssue: "unavailable" }; + return { readiness: { auth: "unknown", connectionIssue: "unavailable" } }; } function connectionIssueNote( @@ -232,11 +266,18 @@ export function registerConnections( loginCommand: loginCommands[harness], }; let auth: WorkerReadiness; + let customIssueNote: string | undefined; if (harness === "codex" && state().settings.localModel) auth = { auth: "local", accountLabel: "Configured local model" }; - else if (harness === "copilot" || harness === "dsh") - auth = await probeStandardConnection(harness, command); - else { + else if (harness === "copilot" || harness === "dsh") { + const probed = await probeStandardConnection( + harness, + command, + harness === "dsh" ? state().settings.dshProfile : undefined, + ); + auth = probed.readiness; + customIssueNote = probed.note; + } else { const args = harness === "codex" ? ["login", "status"] @@ -294,7 +335,7 @@ export function registerConnections( ...auth, approvedAt: approved ? receipt?.approvedAt : undefined, note: connectionIssue - ? connectionIssueNote(harness, connectionIssue) + ? (customIssueNote ?? connectionIssueNote(harness, connectionIssue)) : connected ? connectedNote(authStatus) : approved diff --git a/runtime/workers.ts b/runtime/workers.ts index 26cb089..013055b 100644 --- a/runtime/workers.ts +++ b/runtime/workers.ts @@ -26,6 +26,7 @@ import type { Command } from "./local"; import { commandIdentity } from "./commands"; import type { MemtraceEngine } from "./memtrace"; import { discoverHarnesses } from "./catalog"; +import { inspectDshProfiles } from "./dsh-profiles"; import { assignedHarness, planRoute } from "./router"; import { readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { assertWorkerConnected, connectedRuntimes } from "./worker-connections"; @@ -66,6 +67,7 @@ import { queuedFollowups, settleFollowupQueue, } from "./followup-queue"; +import { SUMMARY_HEADING } from "./sharing/cards/summary"; /** Team claims guard official runs; local Fleet still coordinates source edits. */ export interface TeamWorkerClaims { @@ -104,6 +106,7 @@ export function harnessArgs( briefPath = ".memcode/brief.md", contextConfig?: string, toolArgs: string[] = [], + dshProfile?: string, ): { args: string[]; stdin?: string } { if (id === "codex") return { @@ -156,7 +159,7 @@ export function harnessArgs( ], }; if (id === "copilot") return { args: ["--acp", "--stdio"] }; - if (id === "dsh") return { args: ["--profile", "acp"] }; + if (id === "dsh") return { args: ["--profile", dshProfile?.trim() || "acp"] }; throw new Error("Unsupported worker harness."); } @@ -237,12 +240,15 @@ export class WorkerManager { name: string, ) => Promise = findCommand, private readonly catalog: (only?: WorkItem["harness"]) => Promise = - (only) => discoverHarnesses(false, only), + (only) => + discoverHarnesses(false, only, { + dshProfile: this.state().settings.dshProfile, + }), private readonly browsers?: AgentBrowserManager, private readonly terminals?: TerminalManager, private readonly sessionFactory: typeof startHarnessSession = startHarnessSession, private readonly teamClaims?: TeamWorkerClaims, - private readonly assertAccountSession?: () => void, + private readonly assertAccountSession?: (harness?: WorkItem["harness"]) => void, private readonly mayDispatch: (project?: Project) => boolean = () => true, private readonly telemetry?: WorkerTelemetry, private readonly retrievalAssistant?: () => Promise, @@ -562,7 +568,7 @@ export class WorkerManager { let permissionMode = effectivePermissionMode(task, permissionSettings); // Keep this synchronous with the Preparing transition: account changes // reject active workers, and queued passes use this same entry point. - this.assertAccountSession?.(); + this.assertAccountSession?.(task.harness); // A personal record and an invitation-created record may reuse the same // checkout. Only one project identity may drive its branch at a time. const checkoutKey = (value: string) => @@ -588,7 +594,7 @@ export class WorkerManager { try { await this.reviewStarting(task); continuing(); - this.assertAccountSession?.(); + this.assertAccountSession?.(task.harness); if (task.assignment !== "auto") assertWorkerConnected(this.state(), task.harness); if (isActive(task) || this.children.has(task.id)) @@ -1099,6 +1105,7 @@ export class WorkerManager { "The fleet right now (who is editing what, recent changes, decisions involving you):\n" + contextForPrompt(fleetContext), "If a tool or test command is denied, report that exact blocker and continue independent work. Do not repeatedly try equivalent commands or change permission settings to get around it.", + `End your last message with a short section that starts with the line "${SUMMARY_HEADING}". On a shared project the others read only that section, not this conversation, and they can't open files on this computer, so write it for them in plain words: what you did, what changed, how you checked it, and anything left open. Name files by their path in the project, without links.`, runbookBrief(task.checklist, !!contextConfig), initialContext ? "Initial host context (read constraint continuations before editing):\n" + @@ -1114,6 +1121,17 @@ export class WorkerManager { .join("\n\n"); const briefPath = join(workerRoot, "brief.md").replaceAll("\\", "/"); await writeFile(join(workspace, briefPath), prompt, "utf8"); + if (task.harness === "dsh") { + this.assertAccountSession?.("dsh"); + } + const dshProfile = + task.harness === "dsh" + ? ( + await inspectDshProfiles(this.state().settings.dshProfile).catch( + () => undefined, + ) + )?.activeProfile ?? this.state().settings.dshProfile + : undefined; const invocation = harnessArgs( task.harness, workspace, @@ -1124,6 +1142,7 @@ export class WorkerManager { briefPath, contextConfig, toolProfile.args, + dshProfile, ); continuing(); closeArtifacts = watchArtifacts( @@ -1244,6 +1263,7 @@ export class WorkerManager { effort: task.route.effort, calibratedModel: task.route.selection?.calibratedModel, localModel: task.route.localModel, + ...(launchedHarness === "dsh" ? { dshProfile } : {}), permissionMode, prompt, briefPath, diff --git a/scripts/fixtures/browser-shell.ts b/scripts/fixtures/browser-shell.ts new file mode 100644 index 0000000..def64e3 --- /dev/null +++ b/scripts/fixtures/browser-shell.ts @@ -0,0 +1,58 @@ +// Stands in for the three @tauri-apps/api modules when the app window runs in an +// ordinary browser beside scripts/shared-projects-local.mts. Requests go to that +// script over HTTP instead of to the native shell. +type Listener = (event: { payload: unknown }) => void; + +const listeners = new Map>(); +let showWorkspace: ((state: unknown) => void) | undefined; +let events: EventSource | undefined; + +function listenToRuntime() { + if (events) return; + events = new EventSource("/events"); + events.onmessage = (message) => { + const { event, payload } = JSON.parse(message.data); + if (event === "workspace:state") showWorkspace?.(payload); + else listeners.get(event)?.forEach((listener) => listener({ payload })); + }; +} + +async function rpc(method: string, input: unknown): Promise { + const response = await fetch("/rpc", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method, input }), + }); + const reply = await response.json(); + // The native shell rejects with a string, and src/tauri.ts expects that. + if (reply.error !== undefined) throw reply.error; + return reply.result; +} + +export const isTauri = () => true; + +export class Channel { + onmessage: (message: T) => void = () => {}; +} + +export async function invoke(command: string, args: any = {}): Promise { + if (command === "rpc") return rpc(args.method, args.input) as Promise; + if (command === "workspace_ack") return true as T; + if (command !== "workspace_connect") throw `Unknown command ${command}`; + let sequence = 0; + showWorkspace = (state) => + args.channel.onmessage({ sequence: ++sequence, token: args.token, state }); + listenToRuntime(); + const loaded = (await rpc("workspace:load", null)) as { state: unknown }; + showWorkspace(loaded.state); + return undefined as T; +} + +export async function listen(event: string, listener: Listener) { + if (!listeners.has(event)) listeners.set(event, new Set()); + listeners.get(event)!.add(listener); + listenToRuntime(); + return () => void listeners.get(event)!.delete(listener); +} + +export const getCurrentWindow = () => ({ startDragging: async () => {} }); diff --git a/scripts/macos-release-trust.d.mts b/scripts/macos-release-trust.d.mts index 05a8c46..df8d700 100644 --- a/scripts/macos-release-trust.d.mts +++ b/scripts/macos-release-trust.d.mts @@ -11,3 +11,9 @@ export function macReleasePolicy( env?: Record, ): MacReleasePolicy; export function assertPublicMacTrust(proof: T): T; +/** Native binaries in the bundled `dist-*` folders, other than Node, to sign for public release. */ +export function bundledLibrariesToSign(root: string): Promise; +/** Records signed files' fingerprints in their folder's provenance.json, keeping the unsigned ones. */ +export function recordSignedFiles(root: string, signed: string[]): Promise; +/** Whether Apple notarized a standalone program; Gatekeeper's app assessment cannot tell. */ +export function isNotarizedExecutable(binary: string): boolean; diff --git a/scripts/macos-release-trust.mjs b/scripts/macos-release-trust.mjs index 9795680..e4a1a39 100644 --- a/scripts/macos-release-trust.mjs +++ b/scripts/macos-release-trust.mjs @@ -1,4 +1,4 @@ -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { randomBytes, createHash } from "node:crypto"; import { mkdir, @@ -12,7 +12,7 @@ import { chmod, } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, relative, sep } from "node:path"; const appleKeys = [ "APPLE_CERTIFICATE", @@ -245,6 +245,24 @@ export async function prepareMacSigning(root, inherited = process.env) { node, ]); run("/usr/bin/codesign", ["--verify", "--strict", node]); + // Native libraries in the other bundled folders, such as onnxruntime for local + // search, are loaded by that Node. Apple rejects the app while any is unsigned. + const libraries = await bundledLibrariesToSign(root); + for (const library of libraries) { + run("/usr/bin/codesign", [ + "--force", + "--timestamp", + "--options", + "runtime", + "--sign", + policy.identity, + "--keychain", + keychain, + library, + ]); + run("/usr/bin/codesign", ["--verify", "--strict", library]); + } + await recordSignedFiles(root, libraries); const signedRuntime = { originalExecutableSha256: provenance.executableSha256, signedExecutableSha256: digest(await readFile(node)), @@ -258,6 +276,67 @@ export async function prepareMacSigning(root, inherited = process.env) { } } +/** + * Whether Apple notarized a standalone program, such as the engine's command-line + * tools. Gatekeeper's app assessment rejects anything that is not an app bundle + * ("does not seem to be an app"), so it cannot answer this; codesign can. + */ +export function isNotarizedExecutable(binary) { + return ( + spawnSync( + "/usr/bin/codesign", + ["--verify", "--strict", "--test-requirement==notarized", binary], + { stdio: "ignore" }, + ).status === 0 + ); +} + +/** + * Writes the fingerprint of each signed file into the provenance.json of the bundled + * folder it is in, keeping the unsigned one, since the app checks those files + * against it before it loads them. + */ +export async function recordSignedFiles(root, signed) { + const byFolder = new Map(); + for (const path of signed) { + const [folder, ...rest] = relative(root, path).split(sep); + byFolder.set(folder, [...(byFolder.get(folder) ?? []), rest.join("/")]); + } + for (const [folder, names] of byFolder) { + const manifest = join(root, folder, "provenance.json"); + let provenance; + try { + provenance = JSON.parse(await readFile(manifest, "utf8")); + } catch { + continue; + } + if (!Array.isArray(provenance.files)) continue; + for (const entry of provenance.files) { + if (!names.includes(entry.name)) continue; + const bytes = await readFile(join(root, folder, entry.name)); + entry.unsignedSha256 ??= entry.sha256; + entry.bytes = bytes.length; + entry.sha256 = digest(bytes); + } + await writeFile(manifest, JSON.stringify(provenance, null, 2) + "\n"); + } +} + +/** + * The native binaries in the folders packaging copies into the app as resources + * (`dist-*` at the root), other than Node, which is signed with its own entitlement. + */ +export async function bundledLibrariesToSign(root) { + const node = join(root, "dist-desktop-runtime/node"); + const folders = (await readdir(root, { withFileTypes: true })).filter( + (entry) => entry.isDirectory() && entry.name.startsWith("dist-"), + ); + const found = await Promise.all( + folders.map((folder) => machoFiles(join(root, folder.name))), + ); + return found.flat().filter((path) => path !== node); +} + export async function machoFiles(directory) { const files = []; for (const entry of await readdir(directory, { withFileTypes: true })) { @@ -353,7 +432,6 @@ export async function verifyMacRelease(root, signing) { try { run("/usr/bin/ditto", ["-x", "-k", engineArchive, engineTemp]); const names = ["memtrace", "memcore-server", "memcortex-daemon", "memcortex-mcp"]; - const { spawnSync } = await import("node:child_process"); for (const name of names) { const binary = join(engineTemp, name); const expected = engineManifest.files.find(file => file.name === name); @@ -366,7 +444,8 @@ export async function verifyMacRelease(root, signing) { const details = display.stdout + display.stderr; if (display.status !== 0 || !details.includes("Authority=Developer ID Application:") || !details.includes("TeamIdentifier=" + proof.teamId) || !/flags=.*runtime/.test(details)) throw Error("Public Mac distribution requires separately Developer ID signed, hardened and notarized engine executables. This bundled engine has not established that trust; use an explicitly labelled manual-approval beta until a trusted engine release is pinned."); - run("/usr/sbin/spctl", ["--assess", "--type", "execute", "--verbose=4", binary]); + if (!isNotarizedExecutable(binary)) + throw Error(`Apple has not notarized the bundled engine program ${name}.`); } proof.bundledEngineNativeTrust = { developerIdSigned: true, gatekeeper: "accepted", nativeExecutables: names.length, archiveSha256: engineManifest.sha256 }; } finally { @@ -395,7 +474,6 @@ export async function verifyMacRelease(root, signing) { run("/usr/bin/codesign", ["--verify", "--strict", binary]); // codesign writes metadata to stderr even on success. // Collect both streams without printing any content. - const { spawnSync } = await import("node:child_process"); const display = spawnSync( "/usr/bin/codesign", ["--display", "--verbose=4", binary], diff --git a/scripts/native-browser-smoke.mjs b/scripts/native-browser-smoke.mjs index 47df72c..4c7a4f9 100644 --- a/scripts/native-browser-smoke.mjs +++ b/scripts/native-browser-smoke.mjs @@ -66,6 +66,14 @@ try { } assert.ok(main, "Native main page did not load: " + diagnostics); await main.waitForFunction(() => !!window.memcode); + // A fresh profile opens on the welcome. Close it, as tauri-smoke.mjs does. + const loaded = await main.evaluate(() => window.memcode.load()); + const onboarding = (loaded?.state ?? loaded)?.onboarding; + if (!onboarding || (onboarding.step === "welcome" && !onboarding.dismissed)) { + const skip = main.getByRole("button", { name: "Skip for now", exact: true }); + await expect(skip).toBeVisible(); + await skip.click(); + } await main.evaluate(() => window.memcode.selectProject("example")); await main.getByRole("button", { name: "Workspace", exact: true }).click(); await main diff --git a/scripts/shared-projects-local.mts b/scripts/shared-projects-local.mts new file mode 100644 index 0000000..6a91bb5 --- /dev/null +++ b/scripts/shared-projects-local.mts @@ -0,0 +1,391 @@ +// Runs the real MemCode runtime and the real app window in a browser, signed in +// through a memtrace.io you run on this computer, so sharing can be tried before +// anything is deployed. docs/shared-projects.md has the steps. +// +// What is real: the runtime, its beta sign-in and refresh, the token exchange, +// the gRPC calls to memsync-server and every pixel of the app. +// What stands in: the native shell (this script answers its calls), the person +// in the browser (the script approves the sign-in with the cookie you give it), +// and the code engine, which is switched off. +// +// MEMCODE_LOCAL_SITE=http://127.0.0.1:3000 \ +// MEMCODE_LOCAL_SITE_COOKIE= \ +// node --import tsx scripts/shared-projects-local.mts [--port 5310] [--profile ] +// [--stand-in-worker] +// +// --stand-in-worker adds POST /dev/worker-turn, which plays a worker on a task: +// it adds a turn of the conversation, sets the run's state and can save a file +// the worker made. It also answers follow-ups: one sent to a task, here or from +// another computer, is picked up and answered in a couple of seconds, in place +// of a real worker. Nothing runs a model. Everything else in the app is as it is. +import react from "@vitejs/plugin-react"; +import { build } from "vite"; +import { createServer } from "node:http"; +import { randomUUID } from "node:crypto"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { extname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRuntime } from "../runtime/app.ts"; +import { BETA_ORIGIN } from "../runtime/beta-auth.ts"; +import { ManagedMemcodeEngine } from "../runtime/managed-engine.ts"; +import { MemtraceEngine } from "../runtime/memtrace.ts"; +import { initialState } from "../src/seed.ts"; +import { WorkerManager } from "../runtime/workers.ts"; + +const root = resolve(fileURLToPath(new URL("..", import.meta.url))); +const option = (name: string) => { + const at = process.argv.indexOf(name); + return at < 0 ? undefined : process.argv[at + 1]; +}; +const site = new URL(process.env.MEMCODE_LOCAL_SITE ?? ""); +const cookie = process.env.MEMCODE_LOCAL_SITE_COOKIE; +if (!["localhost", "127.0.0.1", "[::1]"].includes(site.hostname) || !cookie) + throw new Error( + "Set MEMCODE_LOCAL_SITE to a memtrace.io on this computer and MEMCODE_LOCAL_SITE_COOKIE to a signed-in person's session cookie.", + ); +const port = Number(option("--port") ?? 5310); +const profile = resolve( + option("--profile") ?? + (await mkdtemp(join(tmpdir(), "memcode-local-profile-"))), +); +const built = join(profile, "window"); + +// MemCode only ever signs in at memtrace.io. Here, and only here, that name leads to the local site. +const sendToInternet = globalThis.fetch; +const sendToLocalSite: typeof fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : input); + if (url.origin !== BETA_ORIGIN) return sendToInternet(input, init); + return sendToInternet(new URL(url.pathname + url.search, site), init); +}; +globalThis.fetch = sendToLocalSite; + +// No code engine in this run: nothing is downloaded and no installed Memtrace is touched. +ManagedMemcodeEngine.prototype.prepare = async () => join(profile, "no-engine"); +MemtraceEngine.prototype.analyze = async () => { + throw new Error("The code engine is switched off in this local run."); +}; + +/** The person in the browser, approving MemCode's sign-in at the local site. */ +async function approveSignIn(authorizeUrl: string) { + const signedIn = { cookie: `better-auth.session_token=${cookie}` }; + const page = await sendToLocalSite(authorizeUrl, { headers: signedIn }); + const consent = /name="consent" value="([^"]+)"/.exec(await page.text())?.[1]; + if (!consent) + throw new Error( + `The local site showed no approval page (HTTP ${page.status}). Is the cookie for a signed-in, approved person?`, + ); + const approved = await sendToLocalSite( + new URL("/api/memcode/beta/authorize", BETA_ORIGIN), + { + method: "POST", + redirect: "manual", + headers: { + ...signedIn, + origin: BETA_ORIGIN, + "content-type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ + consent, + action: "approve", + accept_terms: "yes", + }), + }, + ); + const backToMemcode = approved.headers.get("location"); + if (!backToMemcode) + throw new Error( + `The local site did not approve (HTTP ${approved.status}).`, + ); + await sendToInternet(backToMemcode); +} + +/** The native shell's part: the credential store, and the pages it would open in a browser. */ +const stored: { + configured: boolean; + signedOut?: boolean; + credentials: unknown; + accessToken?: string; +} = { + configured: false, + credentials: null, +}; +const accessFile = join(profile, "engine-access.jwt"); +const host = { + async call(method: string, input?: any): Promise { + const done = null as T; + if (method === "beta_store_read") + return structuredClone({ + ...stored, + ...(stored.accessToken ? { accessFile } : {}), + }) as T; + if (method === "beta_store_write") { + Object.assign(stored, { + configured: true, + signedOut: false, + credentials: input.credentials, + }); + return done; + } + if (method === "beta_access_write") { + stored.accessToken = input.accessToken; + await writeFile(accessFile, input.accessToken, { mode: 0o600 }); + return { accessFile } as T; + } + if (method === "beta_access_clear") + return void (stored.accessToken = undefined) as T; + if (method === "beta_store_mark_signed_out") + return void Object.assign(stored, { + signedOut: true, + accessToken: undefined, + }) as T; + if (method === "beta_store_forget_session" || method === "beta_store_clear") + return void Object.assign(stored, { + credentials: null, + accessToken: undefined, + }) as T; + if (method === "open_memcode_beta") { + // The shell returns at once and the browser does its part afterwards. + void approveSignIn(input.url).catch((problem) => + console.error(String(problem)), + ); + return done; + } + if (method === "installation_status") + return { + state: "development", + needsInstall: false, + canUpdate: false, + } as T; + console.log( + `[shell] ${method}${method.startsWith("open_") ? " would open a page or folder" : ""}`, + ); + return done; + }, +}; + +// A workspace with one project of its own, so there is something to connect. +await mkdir(join(profile, "website"), { recursive: true }); +try { + await readFile(join(profile, "workspace.json")); +} catch { + const state = initialState(); + state.projects.push({ + id: "local-website", + name: "website", + description: "A local project for trying out sharing.", + path: join(profile, "website"), + branch: "main", + analysis: "idle", + createdAt: new Date().toISOString(), + }); + state.activeProjectId = "local-website"; + await writeFile(join(profile, "workspace.json"), JSON.stringify(state)); +} + +const watchers = new Set<(event: string, payload: unknown) => void>(); +const runtime = await createRuntime(profile, root, host, (event, payload) => + watchers.forEach((tell) => tell(event, payload)), +); + +// The app's own code, with the three Tauri modules replaced by ones that talk to this script. +await build({ + configFile: false, + root, + base: "./", + plugins: [react()], + logLevel: "warn", + resolve: { + alias: Object.fromEntries( + ["core", "event", "window"].map((part) => [ + `@tauri-apps/api/${part}`, + join(root, "scripts/fixtures/browser-shell.ts"), + ]), + ), + }, + build: { outDir: built, emptyOutDir: true, target: "es2023" }, +}); + +/** A worker's turn, played without a model, for trying card activity in two windows. */ +async function playWorker(turn: { + taskId: string; + role?: "user" | "assistant"; + text?: string; + state?: "running" | "finished"; + file?: { name: string; text: string }; +}) { + const state = runtime.store.state; + const task = state.tasks.find((item) => item.id === turn.taskId); + if (!task) throw new Error("No such task here."); + const now = new Date().toISOString(); + if (!task.run.startedAt) task.run = { state: "running", startedAt: now }; + if (turn.state) task.run.state = turn.state; + if (turn.state === "finished") task.run.finishedAt = now; + task.run.activity = + turn.state === "finished" + ? undefined + : ({ + phase: "editing", + label: "Editing project files", + at: now, + } as never); + if (turn.text) + task.messages.push({ + id: randomUUID(), + role: turn.role ?? "assistant", + text: turn.text, + at: now, + }); + if (turn.file) { + const folder = join(profile, "captures", task.id); + await mkdir(folder, { recursive: true }); + const path = join(folder, turn.file.name); + await writeFile(path, turn.file.text); + state.artifacts.push({ + id: randomUUID(), + projectId: task.projectId, + taskId: task.id, + name: turn.file.name, + kind: turn.file.name.endsWith(".html") ? "html" : "text", + path, + createdAt: now, + source: "Worker", + purpose: "report", + }); + } + // Saved as any change is, so sharing hears of it. + await runtime.request("task:update", { id: task.id, patch: {} }); +} + +/** + * In place of a real worker: a follow-up that waits on a task is picked up, and + * a moment later answered. The run keeps its start, so its card shows one run. + */ +const standInWorker = process.argv.includes("--stand-in-worker"); +const ANSWER_AFTER_MS = 2500; +function answerFollowups() { + const state = runtime.store.state; + for (const task of state.tasks) { + const waiting = task.messages.filter( + (message) => message.followupState === "queued" && !message.promptedAt, + ); + if (!waiting.length) continue; + const now = new Date().toISOString(); + for (const message of waiting) { + message.promptedAt = now; + message.followupState = "included"; + } + task.run = { + ...task.run, + state: "running", + startedAt: task.run.startedAt ?? now, + finishedAt: undefined, + activity: { phase: "editing", label: "Editing project files", at: now }, + } as typeof task.run; + void runtime.request("task:update", { id: task.id, patch: {} }); + setTimeout(() => { + void playWorker({ + taskId: task.id, + text: waiting + .map( + (message) => + `Done with “${message.text.split("\n")[0].slice(0, 120)}” (the local stand-in worker answered; no model ran).`, + ) + .join("\n\n"), + state: "finished", + }).catch((problem) => console.error("The stand-in worker failed:", problem)); + }, ANSWER_AFTER_MS); + } +} +if (standInWorker) + WorkerManager.prototype.dispatchQueued = function () { + queueMicrotask(answerFollowups); + }; + +const types: Record = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript", + ".mjs": "text/javascript", + ".wasm": "application/wasm", + ".css": "text/css", + ".svg": "image/svg+xml", + ".png": "image/png", + ".woff2": "font/woff2", + ".json": "application/json", +}; +const origin = `http://127.0.0.1:${port}`; +createServer(async (request, response) => { + const url = new URL(request.url ?? "/", origin); + // Only this page may drive the runtime: no other site, and no request without JSON. + const fromHere = + request.headers.host === `127.0.0.1:${port}` && + (request.headers.origin ?? origin) === origin; + if (!fromHere) return void response.writeHead(403).end(); + if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const part of request) body += part; + const reply = await (async () => { + if ( + !String(request.headers["content-type"]).startsWith("application/json") + ) + return { error: "Send JSON." }; + try { + const { method, input } = JSON.parse(body); + return { + result: (await runtime.request(method, input ?? null)) ?? null, + }; + } catch (problem) { + return { error: (problem as Error).message }; + } + })(); + response.writeHead(200, { "content-type": "application/json" }); + return void response.end(JSON.stringify(reply)); + } + if ( + process.argv.includes("--stand-in-worker") && + request.method === "POST" && + url.pathname === "/dev/worker-turn" + ) { + let body = ""; + for await (const part of request) body += part; + try { + await playWorker(JSON.parse(body)); + response.writeHead(200, { "content-type": "application/json" }); + return void response.end("{}"); + } catch (problem) { + response.writeHead(400, { "content-type": "application/json" }); + return void response.end( + JSON.stringify({ error: (problem as Error).message }), + ); + } + } + if (url.pathname === "/events") { + response.writeHead(200, { + "content-type": "text/event-stream", + "cache-control": "no-store", + }); + const tell = (event: string, payload: unknown) => + response.write(`data: ${JSON.stringify({ event, payload })}\n\n`); + watchers.add(tell); + return void request.on("close", () => watchers.delete(tell)); + } + const name = url.pathname === "/" ? "index.html" : url.pathname.slice(1); + try { + const file = resolve(built, name); + if (!file.startsWith(built)) throw new Error("outside the built window"); + const bytes = await readFile(file); + response.writeHead(200, { + "content-type": types[extname(file)] ?? "application/octet-stream", + }); + response.end(bytes); + } catch { + response.writeHead(404).end(); + } +}).listen(port, "127.0.0.1", () => + console.log( + `MemCode is at ${origin}\n profile: ${profile}\n signs in at: ${site.origin} (stands in for ${BETA_ORIGIN})\n` + + ` finds sharing in: ${new URL("/api/memcode/services", site).href}`, + ), +); +for (const signal of ["SIGINT", "SIGTERM"] as const) + process.on(signal, () => void runtime.close().finally(() => process.exit(0))); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 0917fc0..f006ee8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2350,13 +2350,20 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memcode" -version = "0.4.0-beta.20" +version = "0.4.0-beta.21" dependencies = [ "base64 0.23.1", + "block2", "core-foundation 0.10.1", "dunce", "image", "keyring", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-web-kit", "portable-pty", "rfd", "security-framework", @@ -2636,6 +2643,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", "objc2-quartz-core", "objc2-uniform-type-identifiers", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1f45cc5..68f915d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "memcode" -version = "0.4.0-beta.20" +version = "0.4.0-beta.21" license = "PolyForm-Noncommercial-1.0.0" edition = "2021" rust-version = "1.90" @@ -38,6 +38,14 @@ windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Grap [target.'cfg(target_os = "macos")'.dependencies] security-framework = "=3.7.0" core-foundation = "=0.10.1" +wry = "=0.57.2" +objc2 = "=0.6.5" +block2 = "=0.6.2" +objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSString", "NSError", "NSData", "NSDictionary", "NSValue", "NSProcessInfo", "NSGeometry", "NSRange", "NSObjCRuntime", "NSURL", "NSArray"] } +objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-core-graphics", "NSEvent", "NSView", "NSResponder", "NSWindow", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSGraphicsContext", "NSScreen", "NSTextInputClient"] } +objc2-web-kit = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-app-kit", "objc2-core-foundation", "WKWebView", "WKWebViewConfiguration", "WKContentWorld", "WKFrameInfo", "WKSnapshotConfiguration", "WKContentRuleList", "WKContentRuleListStore", "WKUserContentController", "WKNavigation"] } +objc2-core-graphics = { version = "=0.3.2", default-features = false, features = ["std", "CGEvent", "CGEventTypes", "CGRemoteOperation"] } +objc2-core-foundation = { version = "=0.3.2", default-features = false, features = ["std", "CFCGTypes"] } [profile.release] codegen-units = 1 diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index c892f05..5946c65 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -1,4 +1,5 @@ //! Native browser surfaces. Guest pages receive no Tauri bridge or application RPC. +//! Windows: WebView2 driven over CDP. macOS: WKWebView driven natively (`browser/macos`). use serde_json::{json, Value}; use tauri::{AppHandle, Emitter, Manager}; @@ -479,14 +480,21 @@ mod windows { .map_err(|_| "Native browser operation closed")? } } +#[cfg(target_os = "macos")] +mod macos; + pub async fn call(app: AppHandle, method: &str, input: Value) -> Result { #[cfg(windows)] { windows::call(app, method.to_owned(), input).await } - #[cfg(not(windows))] + #[cfg(target_os = "macos")] + { + macos::call(app, method.to_owned(), input).await + } + #[cfg(not(any(windows, target_os = "macos")))] { let _ = (app, method, input); - Err("The shared native browser currently requires Windows WebView2".into()) + Err("The shared native browser requires Windows WebView2 or macOS WebKit".into()) } } diff --git a/src-tauri/src/browser/macos/address_policy.rs b/src-tauri/src/browser/macos/address_policy.rs new file mode 100644 index 0000000..8c157cb --- /dev/null +++ b/src-tauri/src/browser/macos/address_policy.rs @@ -0,0 +1,127 @@ +//! Which addresses a card page may reach, and the WebKit storage each card gets. +use std::cell::RefCell; + +use block2::RcBlock; +use objc2::{rc::Retained, MainThreadMarker}; +use objc2_foundation::{NSError, NSString}; +use objc2_web_kit::{WKContentRuleList, WKContentRuleListStore}; + +const RULES_IDENTIFIER: &str = "memcode-card-address-policy-1"; +/// Same rule as `browserURL` and the Playwright route: plaintext only to this machine. +/// WebKit's content-blocker patterns have no alternation, so each local host gets a rule. +const RULES: &str = r#"[ + {"trigger": {"url-filter": "^http:"}, "action": {"type": "block"}}, + {"trigger": {"url-filter": "^http://localhost[:/]"}, "action": {"type": "ignore-previous-rules"}}, + {"trigger": {"url-filter": "^http://127\\.0\\.0\\.1[:/]"}, "action": {"type": "ignore-previous-rules"}}, + {"trigger": {"url-filter": "^http://\\[::1\\][:/]"}, "action": {"type": "ignore-previous-rules"}} +]"#; +const PRIVILEGED_HOSTS: [&str; 3] = ["tauri.localhost", "ipc.localhost", "asset.localhost"]; +const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "[::1]", "::1"]; + +thread_local! { + static COMPILED: RefCell>> = const { RefCell::new(None) }; +} + +/// Every navigation, main frame or subframe. Frames also load `about:` and in-page +/// `blob:`/`data:` documents, which never leave the page's own origin. +pub(super) fn navigable(value: &str) -> bool { + if value.is_empty() + || value.starts_with("about:blank") + || value == "about:srcdoc" + || value.starts_with("blob:") + || value.starts_with("data:") + { + return true; + } + let Ok(url) = tauri::Url::parse(value) else { + return false; + }; + let host = url.host_str().unwrap_or(""); + let local_plaintext = url.scheme() == "http" && LOCAL_HOSTS.contains(&host); + !PRIVILEGED_HOSTS.contains(&host) + && url.username().is_empty() + && url.password().is_none() + && (url.scheme() == "https" || local_plaintext) +} + +/// The runtime names a card's profile `worker-`; WebKit wants 16 bytes. +pub(super) fn store_identifier(profile: &str) -> Result<[u8; 16], String> { + let invalid = || "Invalid browser profile".to_string(); + let hex = profile.strip_prefix("worker-").ok_or_else(invalid)?; + if hex.len() < 32 || hex.len() > 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(invalid()); + } + let mut identifier = [0u8; 16]; + for (index, byte) in identifier.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16).map_err(|_| invalid())?; + } + Ok(identifier) +} + +/// Compiles the content rules once, then hands them to `then` on the main thread. +pub(super) fn with_rules(then: impl FnOnce(Result, String>) + 'static) { + if let Some(rules) = COMPILED.with(|compiled| compiled.borrow().clone()) { + return then(Ok(rules)); + } + let Some(store) = MainThreadMarker::new().and_then(|mtm| unsafe { WKContentRuleListStore::defaultStore(mtm) }) else { + return then(Err("WebKit content rules are unavailable".into())); + }; + let then = RefCell::new(Some(then)); + let compiled = RcBlock::new(move |list: *mut WKContentRuleList, error: *mut NSError| { + let Some(then) = then.borrow_mut().take() else { + return; + }; + if list.is_null() { + let reason = if error.is_null() { + "unknown error".to_string() + } else { + unsafe { &*error }.localizedDescription().to_string() + }; + return then(Err(format!("Could not prepare the browser address policy: {reason}"))); + } + let rules = unsafe { Retained::retain(list) }.expect("compiled rule list"); + COMPILED.with(|compiled| *compiled.borrow_mut() = Some(rules.clone())); + then(Ok(rules)); + }); + unsafe { + store.compileContentRuleListForIdentifier_encodedContentRuleList_completionHandler( + Some(&NSString::from_str(RULES_IDENTIFIER)), + Some(&NSString::from_str(RULES)), + Some(&compiled), + ) + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pages_reach_https_and_this_machine_but_not_remote_plaintext_or_the_app() { + assert!(navigable("https://www.google.com/search?q=x")); + assert!(navigable("http://localhost:5173/")); + assert!(navigable("http://127.0.0.1:8080/x")); + assert!(navigable("http://[::1]:3000/")); + assert!(navigable("about:blank")); + assert!(navigable("about:srcdoc")); + assert!(!navigable("http://example.com/")); + assert!(!navigable("http://localhost.:3000/")); + assert!(!navigable("ftp://example.com/")); + assert!(!navigable("file:///etc/hosts")); + assert!(!navigable("tauri://localhost/index.html")); + assert!(!navigable("https://tauri.localhost/")); + assert!(!navigable("https://user:secret@example.com/")); + } + + #[test] + fn a_card_profile_becomes_a_stable_webkit_store_identifier() { + let profile = "worker-00112233445566778899aabbccddeeff0123456789"; + let identifier = store_identifier(profile).unwrap(); + assert_eq!(identifier[0], 0x00); + assert_eq!(identifier[15], 0xff); + assert_eq!(identifier, store_identifier(profile).unwrap()); + assert!(store_identifier("worker-short").is_err()); + assert!(store_identifier("../worker-00112233445566778899aabbccddeeff").is_err()); + assert!(store_identifier("worker-zz112233445566778899aabbccddeeff").is_err()); + } +} diff --git a/src-tauri/src/browser/macos/capture.rs b/src-tauri/src/browser/macos/capture.rs new file mode 100644 index 0000000..397e63f --- /dev/null +++ b/src-tauri/src/browser/macos/capture.rs @@ -0,0 +1,74 @@ +//! Pictures of a card's page from WebKit itself, visible or hidden. +use std::cell::RefCell; + +use base64::Engine; +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject, MainThreadMarker}; +use objc2_app_kit::{NSBitmapImageFileType, NSBitmapImageRep, NSImage, NSImageCompressionFactor, NSView}; +use objc2_foundation::{NSDictionary, NSError, NSNumber}; +use objc2_web_kit::{WKSnapshotConfiguration, WKWebView}; +use serde_json::{json, Value}; + +use super::{surface::{owned, SURFACES}, Reply}; + +/// At Retina density JPEG keeps text readable at about a tenth of PNG's size. +const JPEG_QUALITY: f64 = 0.85; + +pub(super) fn capture(input: &Value, reply: Reply) { + let wk = SURFACES.with(|surfaces| -> Result, String> { + Ok(owned(&mut surfaces.borrow_mut(), input)?.wk.clone()) + }); + let wk = match wk { + Ok(wk) => wk, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + let jpeg = input["format"] == "jpeg"; + let css = input["scale"] == "css"; + let Some(mtm) = MainThreadMarker::new() else { + let _ = reply.send(Err("Browser capture must run on the main thread".into())); + return; + }; + let view: &NSView = &wk; + let size = view.bounds().size; + let backing = view.window().map(|window| window.backingScaleFactor()).unwrap_or(1.0); + let configuration = unsafe { WKSnapshotConfiguration::new(mtm) }; + if css { + // The snapshot width is in points and WebKit renders it at the screen's density. + let width = NSNumber::new_f64(size.width / backing); + unsafe { configuration.setSnapshotWidth(Some(&width)) }; + } + let reply = RefCell::new(Some(reply)); + let taken = RcBlock::new(move |image: *mut NSImage, error: *mut NSError| { + let Some(reply) = reply.borrow_mut().take() else { + return; + }; + let encoded = encode(image, error, jpeg).map(|data| { + json!({ "data": data, "width": size.width, "height": size.height }) + }); + let _ = reply.send(encoded); + }); + unsafe { wk.takeSnapshotWithConfiguration_completionHandler(Some(&configuration), &taken) }; +} + +fn encode(image: *mut NSImage, error: *mut NSError, jpeg: bool) -> Result { + if image.is_null() { + return Err(if error.is_null() { + "The browser returned no image".into() + } else { + unsafe { &*error }.localizedDescription().to_string() + }); + } + let image = unsafe { &*image }; + let tiff = image.TIFFRepresentation().ok_or("The browser image could not be read")?; + let bitmap = NSBitmapImageRep::imageRepWithData(&tiff).ok_or("The browser image could not be read")?; + let quality = NSNumber::new_f64(JPEG_QUALITY); + let quality: &AnyObject = &quality; + let properties = NSDictionary::from_slices(&[unsafe { NSImageCompressionFactor }], &[quality]); + let kind = if jpeg { NSBitmapImageFileType::JPEG } else { NSBitmapImageFileType::PNG }; + let data = unsafe { bitmap.representationUsingType_properties(kind, &properties) } + .ok_or("The browser image could not be encoded")?; + Ok(base64::engine::general_purpose::STANDARD.encode(data.to_vec())) +} diff --git a/src-tauri/src/browser/macos/focus.rs b/src-tauri/src/browser/macos/focus.rs new file mode 100644 index 0000000..0c8b0e6 --- /dev/null +++ b/src-tauri/src/browser/macos/focus.rs @@ -0,0 +1,77 @@ +//! Worker input must not take the human's keyboard. WebKit makes a visible card the +//! window's first responder when a click lands in a text field, a moment after the +//! click. This hands the keyboard back to whatever had it, unless the human has +//! clicked somewhere since. +use std::{ + cell::RefCell, + time::{Duration, Instant}, +}; + +use objc2::{rc::Retained, runtime::AnyObject, Message}; +use objc2_app_kit::{NSResponder, NSView}; +use objc2_web_kit::WKWebView; + +/// WebKit moves focus within a few hundred milliseconds of the click. +const WATCH: Duration = Duration::from_millis(1500); + +struct Borrowed { + card: Retained, + owner: Retained, + since: Instant, +} + +thread_local! { + static BORROWED: RefCell> = const { RefCell::new(None) }; +} + +fn within(responder: &NSResponder, card: &WKWebView) -> bool { + let responder: &AnyObject = responder; + responder + .downcast_ref::() + .is_some_and(|view| view.isDescendantOf(card)) +} + +/// Before worker input: note who has the keyboard if it is not this card. +pub(super) fn remember(card: &WKWebView) { + let Some(owner) = card.window().and_then(|window| window.firstResponder()) else { + return; + }; + if within(&owner, card) { + return; + } + let card = card.retain(); + BORROWED.with(|borrowed| { + *borrowed.borrow_mut() = Some(Borrowed { card, owner, since: Instant::now() }) + }); +} + +/// Runs on every browser call: returns the keyboard if the card took it. +pub(super) fn give_back() { + BORROWED.with(|borrowed| { + let Ok(mut slot) = borrowed.try_borrow_mut() else { + return; + }; + let Some(pending) = slot.as_ref() else { + return; + }; + let Some(window) = pending.card.window() else { + *slot = None; + return; + }; + if window.firstResponder().is_some_and(|now| within(&now, &pending.card)) { + window.makeFirstResponder(Some(&pending.owner)); + *slot = None; + } else if pending.since.elapsed() > WATCH { + *slot = None; + } + }); +} + +/// The human clicked: wherever focus goes now is their choice. +pub(super) fn forget() { + BORROWED.with(|borrowed| { + if let Ok(mut slot) = borrowed.try_borrow_mut() { + *slot = None; + } + }); +} diff --git a/src-tauri/src/browser/macos/human_input.rs b/src-tauri/src/browser/macos/human_input.rs new file mode 100644 index 0000000..d48dfca --- /dev/null +++ b/src-tauri/src/browser/macos/human_input.rs @@ -0,0 +1,86 @@ +//! Notices the human's own clicks, keys and scrolling in a card surface. +//! +//! Real input passes through `NSApplication.sendEvent`, where local monitors run. +//! Worker input is handed straight to the WKWebView, so it never shows up here and +//! no time-window guess is needed to tell the two apart. +use std::{cell::RefCell, ptr::NonNull}; + +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject}; +use objc2_app_kit::{NSEvent, NSEventMask, NSEventType, NSView}; +use serde_json::json; +use tauri::{AppHandle, Emitter}; + +use super::surface::{Surface, SURFACES}; + +thread_local! { + static MONITOR: RefCell>> = const { RefCell::new(None) }; +} + +pub(super) fn watch(app: &AppHandle) { + MONITOR.with(|monitor| { + if monitor.borrow().is_some() { + return; + } + let app = app.clone(); + let seen = RcBlock::new(move |event: NonNull| -> *mut NSEvent { + let event_ref = unsafe { event.as_ref() }; + if event_ref.r#type() != NSEventType::KeyDown && event_ref.r#type() != NSEventType::ScrollWheel { + super::focus::forget(); + } + if let Some(owner) = receiving_owner(event_ref) { + let _ = app.emit_to( + tauri::EventTarget::Webview { label: "main".into() }, + "browser:native-input", + json!({ "taskId": owner, "at": millis() }), + ); + } + event.as_ptr() + }); + let mask = NSEventMask::LeftMouseDown + | NSEventMask::RightMouseDown + | NSEventMask::OtherMouseDown + | NSEventMask::KeyDown + | NSEventMask::ScrollWheel; + *monitor.borrow_mut() = + unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(mask, &seen) }; + }); +} + +fn millis() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +fn receiving_owner(event: &NSEvent) -> Option { + SURFACES.with(|surfaces| { + let surfaces = surfaces.try_borrow().ok()?; + surfaces + .values() + .find(|surface| receives(surface, event)) + .map(|surface| surface.owner.clone()) + }) +} + +fn receives(surface: &Surface, event: &NSEvent) -> bool { + let view: &NSView = &surface.wk; + let Some(window) = view.window() else { + return false; + }; + if view.isHiddenOrHasHiddenAncestor() || event.windowNumber() != window.windowNumber() { + return false; + } + if event.r#type() == NSEventType::KeyDown { + return window.firstResponder().is_some_and(|responder| { + let responder: &AnyObject = &responder; + responder + .downcast_ref::() + .is_some_and(|responder| responder.isDescendantOf(view)) + }); + } + let point = view.convertPoint_fromView(event.locationInWindow(), None); + let bounds = view.bounds(); + point.x >= 0.0 && point.y >= 0.0 && point.x <= bounds.size.width && point.y <= bounds.size.height +} diff --git a/src-tauri/src/browser/macos/input.rs b/src-tauri/src/browser/macos/input.rs new file mode 100644 index 0000000..cb706fb --- /dev/null +++ b/src-tauri/src/browser/macos/input.rs @@ -0,0 +1,164 @@ +//! The worker's mouse, wheel and keyboard input, handed straight to a card's WKWebView. +//! WebKit delivers these to the page as trusted events at the given CSS point. +use objc2::{msg_send, rc::Retained, MainThreadMarker}; +use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType, NSScreen, NSView}; +use objc2_core_foundation::CGPoint; +use objc2_core_graphics::{CGEvent, CGScrollEventUnit}; +use objc2_foundation::{NSNotFound, NSPoint, NSProcessInfo, NSRange, NSString}; +use objc2_web_kit::WKWebView; +use serde_json::Value; + +const MAX_SCROLL: f64 = 4000.0; + +struct Key { + code: u16, + characters: &'static str, + ignoring: &'static str, + flags: NSEventModifierFlags, +} + +pub(super) fn deliver(wk: &WKWebView, input: &Value) -> Result<(), String> { + let point = || -> Result { + let x = input["x"].as_f64().ok_or("Missing x")?; + let y = input["y"].as_f64().ok_or("Missing y")?; + Ok(window_point(wk, x, y)) + }; + match input["kind"].as_str() { + Some("click") => click(wk, point()?)?, + Some("move") => { + let moved = mouse(wk, NSEventType::MouseMoved, point()?, 0)?; + wk.mouseMoved(&moved) + } + Some("wheel") => { + let delta = input["deltaY"].as_f64().unwrap_or(600.0).clamp(-MAX_SCROLL, MAX_SCROLL); + wheel(wk, point()?, delta)? + } + Some("key") => press(wk, input["key"].as_str().ok_or("Missing key")?)?, + Some("text") => insert_text(wk, input["text"].as_str().ok_or("Missing text")?), + _ => return Err("Unknown browser input".into()), + } + Ok(()) +} + +/// A CSS point in the page, as AppKit window coordinates. WKWebView is flipped. +fn window_point(wk: &WKWebView, x: f64, y: f64) -> NSPoint { + let view: &NSView = wk; + let local = if view.isFlipped() { + NSPoint::new(x, y) + } else { + NSPoint::new(x, view.bounds().size.height - y) + }; + view.convertPoint_toView(local, None) +} + +fn window_number(wk: &WKWebView) -> Result { + Ok(wk.window().ok_or("The card browser is not in a window")?.windowNumber()) +} + +fn uptime() -> f64 { + NSProcessInfo::processInfo().systemUptime() +} + +fn mouse(wk: &WKWebView, kind: NSEventType, at: NSPoint, clicks: isize) -> Result, String> { + NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure( + kind, + at, + NSEventModifierFlags::empty(), + uptime(), + window_number(wk)?, + None, + 0, + clicks, + 1.0, + ) + .ok_or_else(|| "Could not create a mouse event".into()) +} + +fn click(wk: &WKWebView, at: NSPoint) -> Result<(), String> { + let (moved, down, up) = ( + mouse(wk, NSEventType::MouseMoved, at, 0)?, + mouse(wk, NSEventType::LeftMouseDown, at, 1)?, + mouse(wk, NSEventType::LeftMouseUp, at, 1)?, + ); + wk.mouseMoved(&moved); + wk.mouseDown(&down); + wk.mouseUp(&up); + Ok(()) +} + +/// With no window attached, NSEvent reports a CG event's flipped location as its +/// window location, which is what WebKit hit-tests against. +fn wheel(wk: &WKWebView, at: NSPoint, delta_y: f64) -> Result<(), String> { + let mtm = MainThreadMarker::new().ok_or("Browser input must run on the main thread")?; + let primary = NSScreen::screens(mtm).firstObject().ok_or("No screen")?.frame(); + let event = CGEvent::new_scroll_wheel_event2(None, CGScrollEventUnit::Pixel, 1, -delta_y.round() as i32, 0, 0) + .ok_or("Could not create a scroll event")?; + CGEvent::set_location(Some(&event), CGPoint { x: at.x, y: primary.size.height - at.y }); + let event = NSEvent::eventWithCGEvent(&event).ok_or("Could not create a scroll event")?; + wk.scrollWheel(&event); + Ok(()) +} + +fn key(name: &str) -> Option { + let plain = NSEventModifierFlags::empty(); + let function = NSEventModifierFlags::Function; + let arrow = NSEventModifierFlags::Function | NSEventModifierFlags::NumericPad; + let key = |code, characters, ignoring, flags| Key { code, characters, ignoring, flags }; + Some(match name { + "Enter" => key(36, "\r", "\r", plain), + "Tab" => key(48, "\t", "\t", plain), + "Shift+Tab" => key(48, "\u{19}", "\u{19}", NSEventModifierFlags::Shift), + "Escape" => key(53, "\u{1b}", "\u{1b}", plain), + "Backspace" => key(51, "\u{7f}", "\u{7f}", plain), + "Delete" => key(117, "\u{f728}", "\u{f728}", function), + "ArrowLeft" => key(123, "\u{f702}", "\u{f702}", arrow), + "ArrowRight" => key(124, "\u{f703}", "\u{f703}", arrow), + "ArrowUp" => key(126, "\u{f700}", "\u{f700}", arrow), + "ArrowDown" => key(125, "\u{f701}", "\u{f701}", arrow), + "Home" => key(115, "\u{f729}", "\u{f729}", function), + "End" => key(119, "\u{f72b}", "\u{f72b}", function), + "PageUp" => key(116, "\u{f72c}", "\u{f72c}", function), + "PageDown" => key(121, "\u{f72d}", "\u{f72d}", function), + "Space" => key(49, " ", " ", plain), + "Control+A" => key(0, "\u{1}", "a", NSEventModifierFlags::Control), + "Meta+A" => key(0, "a", "a", NSEventModifierFlags::Command), + _ => return None, + }) +} + +fn press(wk: &WKWebView, name: &str) -> Result<(), String> { + let key = key(name).ok_or("A supported key is required.")?; + let window = window_number(wk)?; + let event = |kind| { + NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode( + kind, + NSPoint::new(0.0, 0.0), + key.flags, + uptime(), + window, + None, + &NSString::from_str(key.characters), + &NSString::from_str(key.ignoring), + false, + key.code, + ) + .ok_or_else(|| "Could not create a key event".to_string()) + }; + let down = event(NSEventType::KeyDown)?; + // Command shortcuts are key equivalents in AppKit, not ordinary key presses. + if key.flags.contains(NSEventModifierFlags::Command) { + wk.performKeyEquivalent(&down); + } else { + wk.keyDown(&down); + } + let up = event(NSEventType::KeyUp)?; + wk.keyUp(&up); + Ok(()) +} + +/// Text input as the input method would deliver it: one trusted `input` event. +fn insert_text(wk: &WKWebView, text: &str) { + let text = NSString::from_str(text); + let range = NSRange::new(NSNotFound as usize, 0); + let _: () = unsafe { msg_send![wk, insertText: &*text, replacementRange: range] }; +} diff --git a/src-tauri/src/browser/macos/mod.rs b/src-tauri/src/browser/macos/mod.rs new file mode 100644 index 0000000..73c1b0e --- /dev/null +++ b/src-tauri/src/browser/macos/mod.rs @@ -0,0 +1,42 @@ +//! macOS card browsers: a real WKWebView over the card, one WebKit data store per card. +//! Guest pages get no bridge at all. MemCode's own scripts run in a separate content +//! world, and worker input is delivered to the view directly, never through the app's +//! event queue, so only the human's own input reaches `human_input`. +mod address_policy; +mod capture; +mod focus; +mod human_input; +mod input; +mod script; +mod self_close; +mod surface; + +use serde_json::Value; +use tauri::AppHandle; +use tokio::sync::oneshot; + +type Reply = oneshot::Sender>; + +pub async fn call(app: AppHandle, method: String, input: Value) -> Result { + let (reply, answer) = oneshot::channel(); + let main = app.clone(); + app.run_on_main_thread(move || dispatch(&main, &method, input, reply)) + .map_err(|e| e.to_string())?; + tokio::time::timeout(std::time::Duration::from_secs(25), answer) + .await + .map_err(|_| "Native browser operation timed out")? + .map_err(|_| "Native browser operation closed")? +} + +fn dispatch(app: &AppHandle, method: &str, input: Value, reply: Reply) { + focus::give_back(); + surface::remove_self_closed(); + match method { + "browser_create" => surface::create(app, input, reply), + "browser_capture" => capture::capture(&input, reply), + "browser_eval" => script::evaluate(&input, reply), + _ => { + let _ = reply.send(surface::operate(method, &input)); + } + } +} diff --git a/src-tauri/src/browser/macos/script.rs b/src-tauri/src/browser/macos/script.rs new file mode 100644 index 0000000..935f823 --- /dev/null +++ b/src-tauri/src/browser/macos/script.rs @@ -0,0 +1,81 @@ +//! MemCode's own page scripts. They run in a separate WebKit content world: they share +//! the page's DOM but none of its JavaScript, so a page can neither see nor patch them. +use std::cell::RefCell; + +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject, MainThreadMarker}; +use objc2_foundation::{NSError, NSString}; +use objc2_web_kit::{WKContentWorld, WKWebView}; +use serde_json::{json, Value}; + +use super::{surface::{owned, SURFACES}, Reply}; + +const WORLD: &str = "memcode"; +const MAX_SCRIPT: usize = 512 * 1024; + +thread_local! { + /// WebKit drops a content world's JavaScript state once the API object is + /// released, so the driver's per-page state lives only as long as this does. + static MEMCODE_WORLD: RefCell>> = const { RefCell::new(None) }; +} + +fn memcode_world(mtm: MainThreadMarker) -> Retained { + MEMCODE_WORLD.with(|world| { + world + .borrow_mut() + .get_or_insert_with(|| unsafe { WKContentWorld::worldWithName(&NSString::from_str(WORLD), mtm) }) + .clone() + }) +} + +/// Runs an async function body; it must return a string (the runtime sends JSON). +pub(super) fn evaluate(input: &Value, reply: Reply) { + let prepared = (|| -> Result<(Retained, Retained, String), String> { + let body = input["script"].as_str().ok_or("Missing browser script")?; + if body.len() > MAX_SCRIPT { + return Err("Browser script is too large".into()); + } + let wk = SURFACES.with(|surfaces| -> Result<_, String> { + Ok(owned(&mut surfaces.borrow_mut(), input)?.wk.clone()) + })?; + let mtm = MainThreadMarker::new().ok_or("Browser scripts must run on the main thread")?; + Ok((wk, memcode_world(mtm), body.to_owned())) + })(); + let (wk, world, body) = match prepared { + Ok(prepared) => prepared, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + let reply = RefCell::new(Some(reply)); + let finished = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| { + let Some(reply) = reply.borrow_mut().take() else { + return; + }; + let _ = reply.send(answer(result, error)); + }); + unsafe { + wk.callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler( + &NSString::from_str(&body), + None, + None, + &world, + Some(&finished), + ) + }; +} + +fn answer(result: *mut AnyObject, error: *mut NSError) -> Result { + if !error.is_null() { + return Err(unsafe { &*error }.localizedDescription().to_string()); + } + if result.is_null() { + return Ok(Value::Null); + } + let result = unsafe { &*result }; + result + .downcast_ref::() + .map(|text| json!(text.to_string())) + .ok_or_else(|| "Browser scripts must return text".into()) +} diff --git a/src-tauri/src/browser/macos/self_close.rs b/src-tauri/src/browser/macos/self_close.rs new file mode 100644 index 0000000..681dbe7 --- /dev/null +++ b/src-tauri/src/browser/macos/self_close.rs @@ -0,0 +1,171 @@ +//! A page's `window.close()`. wry's UI delegate has no `webViewDidClose:`, so WebKit's +//! request to close a page went unheard and the page stayed open as a tab. This delegate +//! sits in front of wry's: it notes the request and passes every other UI delegate +//! message to wry's unchanged, so popups, uploads and the camera and microphone denial +//! work as before. +use std::cell::Cell; + +use objc2::{ + define_class, msg_send, + rc::Retained, + runtime::{AnyObject, Bool, NSObject, Sel}, + AllocAnyThread, DefinedClass, +}; +use objc2_web_kit::WKWebView; + +pub(super) struct Ivars { + wry: Option>, + requested: Cell, +} + +define_class!( + #[unsafe(super(NSObject))] + #[name = "MemCodeSelfCloseListener"] + #[ivars = Ivars] + pub(super) struct SelfCloseListener; + + impl SelfCloseListener { + #[unsafe(method(webViewDidClose:))] + fn web_view_did_close(&self, _page: &AnyObject) { + self.ivars().requested.set(true); + } + + /// WebKit asks once, when the delegate is set, which messages it may send. + #[unsafe(method(respondsToSelector:))] + fn responds_to_selector(&self, selector: Sel) -> Bool { + let own: Bool = unsafe { msg_send![super(self), respondsToSelector: selector] }; + Bool::new(own.as_bool() || self.wry_handles(selector)) + } + + #[unsafe(method(forwardingTargetForSelector:))] + fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject { + match &self.ivars().wry { + Some(wry) if self.wry_handles(selector) => Retained::as_ptr(wry).cast_mut(), + _ => std::ptr::null_mut(), + } + } + } +); + +impl SelfCloseListener { + fn wry_handles(&self, selector: Sel) -> bool { + self.ivars().wry.as_deref().is_some_and(|wry| { + let answer: Bool = unsafe { msg_send![wry, respondsToSelector: selector] }; + answer.as_bool() + }) + } + + fn new(wry: Option>) -> Retained { + let listener = Self::alloc().set_ivars(Ivars { wry, requested: Cell::new(false) }); + unsafe { msg_send![super(listener), init] } + } + + /// Puts a listener in front of the view's UI delegate. The caller keeps it alive: + /// WebKit holds UI delegates weakly. + pub(super) fn install(wk: &WKWebView) -> Retained { + let wry: Option> = unsafe { msg_send![wk, UIDelegate] }; + let listener = Self::new(wry); + let _: () = unsafe { msg_send![wk, setUIDelegate: &*listener] }; + listener + } + + /// The page asked to close itself. + pub(super) fn requested(&self) -> bool { + self.ivars().requested.get() + } +} + +#[cfg(test)] +mod tests { + use std::{ffi::CStr, rc::Rc}; + + use block2::{Block, RcBlock}; + use objc2::{sel, ClassType}; + + use super::*; + + const CAMERA: isize = 0; + const DENY: isize = 2; + const MEDIA_PERMISSION: &CStr = + c"webView:requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:"; + + // Stands in for wry's delegate: denies camera and microphone, as MemCode's handler does. + define_class!( + #[unsafe(super(NSObject))] + #[name = "MemCodeTestWryUIDelegate"] + struct FakeWryDelegate; + + impl FakeWryDelegate { + #[unsafe(method(webView:requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:))] + fn request_media_capture_permission( + &self, + _page: &AnyObject, + _origin: &AnyObject, + _frame: &AnyObject, + _kind: isize, + decide: &Block, + ) { + decide.call((DENY,)); + } + } + ); + + fn listener() -> Retained { + let wry: Retained = unsafe { msg_send![FakeWryDelegate::class(), new] }; + SelfCloseListener::new(Some(wry)) + } + + fn answers(delegate: &AnyObject, selector: Sel) -> bool { + let answer: Bool = unsafe { msg_send![delegate, respondsToSelector: selector] }; + answer.as_bool() + } + + /// Sends the request the way WebKit does. objc2's debug check would refuse it, + /// because the listener's own class lacks the method; forwarding is what is tested. + fn ask_for_camera(delegate: &AnyObject, decide: &Block) { + type Send = unsafe extern "C-unwind" fn( + &AnyObject, + Sel, + &AnyObject, + &AnyObject, + &AnyObject, + isize, + &Block, + ); + let send: Send = unsafe { std::mem::transmute(objc2::ffi::objc_msgSend as *const ()) }; + let stand_in = NSObject::new(); + let selector = Sel::register(MEDIA_PERMISSION); + unsafe { send(delegate, selector, &stand_in, &stand_in, &stand_in, CAMERA, decide) }; + } + + #[test] + fn notes_a_page_closing_itself() { + let listener = listener(); + assert!(!listener.requested()); + assert!(answers(&listener, sel!(webViewDidClose:))); + + let page = NSObject::new(); + let _: () = unsafe { msg_send![&*listener, webViewDidClose: &*page] }; + + assert!(listener.requested()); + } + + #[test] + fn camera_requests_still_reach_wrys_handler() { + let listener = listener(); + assert!(answers(&listener, Sel::register(MEDIA_PERMISSION))); + + let decided = Rc::new(Cell::new(None)); + let record = decided.clone(); + let decide = RcBlock::new(move |decision: isize| record.set(Some(decision))); + ask_for_camera(&listener, &decide); + + assert_eq!(decided.get(), Some(DENY)); + } + + #[test] + fn claims_nothing_wry_does_not_handle() { + let alerts = sel!(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:); + assert!(!answers(&listener(), alerts)); + } +} diff --git a/src-tauri/src/browser/macos/surface.rs b/src-tauri/src/browser/macos/surface.rs new file mode 100644 index 0000000..880f5ec --- /dev/null +++ b/src-tauri/src/browser/macos/surface.rs @@ -0,0 +1,310 @@ +//! Card surfaces: create, place, show, hide and close the WKWebViews over cards. +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + rc::Rc, + sync::atomic::{AtomicU64, Ordering}, +}; + +use objc2::rc::Retained; +use objc2_web_kit::{WKContentRuleList, WKWebView, WKWebViewConfiguration}; +use serde_json::{json, Value}; +use tauri::{AppHandle, Manager}; +use wry::{ + BackgroundThrottlingPolicy, NewWindowFeatures, NewWindowResponse, PageLoadEvent, + PermissionResponse, Rect, WebView, WebViewBuilder, WebViewBuilderExtDarwin, + WebViewBuilderExtMacos, WebViewExtMacOS, +}; + +use super::{address_policy, focus, human_input, input, self_close::SelfCloseListener, Reply}; +use crate::native::Bounds; + +const INITIAL_BOUNDS: Bounds = Bounds { + x: 0.0, + y: 0.0, + width: 1280.0, + height: 800.0, +}; +const MAX_SIDE: f64 = 10000.0; + +pub(super) struct Surface { + pub owner: String, + pub wk: Retained, + opener: Option, + view: WebView, + bounds: Bounds, + visible: bool, + loads: Rc>, + self_close: Retained, +} + +thread_local! { + pub(super) static SURFACES: RefCell> = RefCell::new(HashMap::new()); +} +static NEXT: AtomicU64 = AtomicU64::new(1); + +enum Configuration { + Card { + store: [u8; 16], + rules: Retained, + }, + /// A page's `window.open`: WebKit requires the opener's configuration. + Popup(Retained), +} + +fn next_id() -> String { + format!("native-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +fn rect(bounds: Bounds) -> Rect { + Rect { + position: wry::dpi::LogicalPosition::new(bounds.x, bounds.y).into(), + size: wry::dpi::LogicalSize::new(bounds.width, bounds.height).into(), + } +} + +pub(super) fn create(app: &AppHandle, input: Value, reply: Reply) { + let request = (|| -> Result<(String, [u8; 16]), String> { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let profile = input["profile"].as_str().ok_or("Missing browser profile")?; + Ok((owner.to_owned(), address_policy::store_identifier(profile)?)) + })(); + let (owner, store) = match request { + Ok(request) => request, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + human_input::watch(app); + let app = app.clone(); + address_policy::with_rules(move |rules| { + let created = rules.and_then(|rules| { + let id = next_id(); + let surface = build(&app, Configuration::Card { store, rules }, &owner, None, &id)?; + SURFACES.with(|surfaces| surfaces.borrow_mut().insert(id.clone(), surface)); + Ok(json!({ "nativeId": id })) + }); + let _ = reply.send(created); + }); +} + +fn build( + app: &AppHandle, + configuration: Configuration, + owner: &str, + opener: Option, + id: &str, +) -> Result { + let window = app.get_window("main").ok_or("Main window is unavailable")?; + let loads = Rc::new(Cell::new(0u64)); + let committed = loads.clone(); + let popup_app = app.clone(); + let popup_owner = owner.to_owned(); + let popup_opener = id.to_owned(); + let builder = WebViewBuilder::new() + .with_visible(false) + .with_focused(false) + .with_bounds(rect(INITIAL_BOUNDS)) + .with_background_throttling(BackgroundThrottlingPolicy::Disabled) + .with_navigation_handler(|url| address_policy::navigable(&url)) + .with_new_window_req_handler(move |url, features| { + open_popup(&popup_app, &popup_owner, &popup_opener, &url, features) + }) + .with_download_started_handler(|_, _| false) + .with_permission_handler(|_| PermissionResponse::Deny) + .with_on_page_load_handler(move |event, _| { + if matches!(event, PageLoadEvent::Started) { + committed.set(committed.get() + 1); + } + }); + let (builder, rules) = match configuration { + Configuration::Card { store, rules } => { + (builder.with_data_store_identifier(store), Some(rules)) + } + Configuration::Popup(shared) => (builder.with_webview_configuration(shared), None), + }; + let view = builder.build_as_child(&window).map_err(|e| e.to_string())?; + if let Some(rules) = rules { + unsafe { view.manager().addContentRuleList(&rules) }; + } + let wk = Retained::into_super(view.webview()); + let self_close = SelfCloseListener::install(&wk); + Ok(Surface { + owner: owner.to_owned(), + wk, + opener, + view, + bounds: INITIAL_BOUNDS, + visible: false, + loads, + self_close, + }) +} + +/// Drops the pages that called `window.close()`. This runs at the start of a browser +/// call, outside WebKit's own callback. The runtime then sees them missing from +/// `browser_pages` and closes their tabs. +pub(super) fn remove_self_closed() { + SURFACES.with(|surfaces| { + if let Ok(mut surfaces) = surfaces.try_borrow_mut() { + surfaces.retain(|_, surface| !surface.self_close.requested()); + } + }); +} + +fn open_popup( + app: &AppHandle, + owner: &str, + opener: &str, + url: &str, + features: NewWindowFeatures, +) -> NewWindowResponse { + if !address_policy::navigable(url) { + return NewWindowResponse::Deny; + } + let id = next_id(); + let configuration = Configuration::Popup(features.opener.target_configuration); + let Ok(surface) = build(app, configuration, owner, Some(opener.to_owned()), &id) else { + return NewWindowResponse::Deny; + }; + let webview = surface.wk.clone(); + let adopted = SURFACES.with(|surfaces| { + surfaces + .try_borrow_mut() + .map(|mut surfaces| surfaces.insert(id, surface)) + .is_ok() + }); + if adopted { + NewWindowResponse::Create { webview } + } else { + NewWindowResponse::Deny + } +} + +fn place(surface: &Surface) -> Result<(), String> { + surface.view.set_bounds(rect(surface.bounds)).map_err(|e| e.to_string())?; + surface.view.set_visible(surface.visible).map_err(|e| e.to_string()) +} + +fn page_state(id: &str, surface: &Surface) -> Value { + let url = unsafe { surface.wk.URL() } + .and_then(|url| url.absoluteString()) + .map(|url| url.to_string()) + .unwrap_or_else(|| "about:blank".into()); + let title = unsafe { surface.wk.title() }.map(|title| title.to_string()).unwrap_or_default(); + json!({ + "nativeId": id, + "opener": surface.opener, + "url": url, + "title": title, + "loading": unsafe { surface.wk.isLoading() }, + "loads": surface.loads.get(), + }) +} + +fn valid_bounds(value: &Value) -> Result { + let bounds: Bounds = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; + let finite = [bounds.x, bounds.y, bounds.width, bounds.height].iter().all(|n| n.is_finite()); + if !finite + || bounds.x < 0.0 + || bounds.y < 0.0 + || bounds.width < 1.0 + || bounds.height < 1.0 + || bounds.width > MAX_SIDE + || bounds.height > MAX_SIDE + { + return Err("Invalid native browser bounds".into()); + } + Ok(bounds) +} + +/// Looks up a surface the given work item owns. +pub(super) fn owned<'a>( + surfaces: &'a mut HashMap, + input: &Value, +) -> Result<&'a mut Surface, String> { + let id = input["nativeId"].as_str().ok_or("Missing browser surface")?; + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let surface = surfaces.get_mut(id).ok_or("Browser surface not found")?; + if surface.owner != owner { + return Err("Browser surface belongs to another work item".into()); + } + Ok(surface) +} + +pub(super) fn operate(method: &str, input: &Value) -> Result { + SURFACES.with(|surfaces| { + let mut surfaces = surfaces.borrow_mut(); + match method { + "browser_hide_all" => { + for surface in surfaces.values_mut() { + surface.visible = false; + place(surface)?; + } + } + "browser_close_all" => surfaces.clear(), + "browser_close_task" => { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + surfaces.retain(|_, surface| surface.owner != owner); + } + "browser_pages" => { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let pages: Vec = surfaces + .iter() + .filter(|(_, surface)| surface.owner == owner) + .map(|(id, surface)| page_state(id, surface)) + .collect(); + return Ok(Value::Array(pages)); + } + "browser_close" => { + owned(&mut surfaces, input)?; + surfaces.remove(input["nativeId"].as_str().unwrap_or_default()); + } + "browser_surface" => show(&mut surfaces, input)?, + "browser_navigate" => { + let url = input["url"].as_str().ok_or("Missing address")?; + if !address_policy::navigable(url) || url.starts_with("data:") || url.starts_with("blob:") { + return Err("Open an HTTPS website or a localhost development server.".into()); + } + owned(&mut surfaces, input)?.view.load_url(url).map_err(|e| e.to_string())?; + } + "browser_history" => { + let surface = owned(&mut surfaces, input)?; + let _ = match input["action"].as_str() { + Some("back") => unsafe { surface.wk.goBack() }, + Some("forward") => unsafe { surface.wk.goForward() }, + Some("reload") => unsafe { surface.wk.reload() }, + _ => return Err("Unknown browser history action".into()), + }; + } + "browser_input" => { + let card = &owned(&mut surfaces, input)?.wk; + focus::remember(card); + input::deliver(card, &input["input"])? + } + _ => return Err("Unknown browser surface operation".into()), + } + Ok(Value::Null) + }) +} + +/// Shows one card's tab and hides every other surface, as on Windows. +fn show(surfaces: &mut HashMap, input: &Value) -> Result<(), String> { + let visible = input["visible"].as_bool().unwrap_or(false); + let bounds = if visible { Some(valid_bounds(&input["bounds"])?) } else { None }; + owned(surfaces, input)?; + let shown = input["nativeId"].as_str().unwrap_or_default(); + for (id, other) in surfaces.iter_mut() { + if id != shown { + other.visible = false; + place(other)?; + } + } + let surface = owned(surfaces, input)?; + if let Some(bounds) = bounds { + surface.bounds = bounds; + } + surface.visible = visible; + place(surface) +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 391a1d5..8a08b1f 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "MemCode", - "version": "0.4.0-beta.20", + "version": "0.4.0-beta.21", "identifier": "com.memtrace.memcode", "build": { "frontendDist": "../dist", diff --git a/src/App.tsx b/src/App.tsx index 49ea74b..7062d0b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -74,8 +74,19 @@ import { import type { GuideDestination } from "./guide-content"; import { WorkerConnections } from "./components/WorkerConnections"; import { TeamOnboarding } from "./components/TeamOnboarding"; +import { + NoFolderYet, + SHARED_GROUP, + ShareButton, + SwitcherShared, + isSharedHere, + offersSharing, + useSharingOverview, +} from "./components/ShareProject"; +import { LocalProjectSetup } from "./components/LocalProjectSetup"; import "./styles-team.css"; import "./styles-collaboration.css"; +import "./styles-sharing.css"; import { BetaAccess } from "./components/BetaAccess"; import { AppUpdateAction } from "./components/AppUpdates"; import { InstallationGuide } from "./components/InstallationGuide"; @@ -94,6 +105,8 @@ import { SearchDialog, SettingsDialog, } from "./components/Dialogs"; +import { hasTeamPage } from "./team-presentation"; +import { DeleteProject } from "./components/DeleteProject"; type View = | "board" @@ -203,6 +216,10 @@ export function App() { const [toast, setToast] = useState(""); const [fatal, setFatal] = useState(""); const [collapsed, setCollapsed] = useState(false); + const [folderSetupOpen, setFolderSetupOpen] = useState(false); + const sharing = useSharingOverview( + betaStatus?.state === "connected" ? betaStatus.account?.id : undefined, + ); const notify = useCallback((message: string) => { setToast(message); }, []); @@ -602,13 +619,18 @@ export function App() { count: groupedArtifacts(artifacts).primary.length, }, { id: "activity", label: "Activity", icon: Radio }, - { - id: "team", - label: "Team", - icon: Users, - count: state.team?.find((item) => item.projectId === project.id) - ?.unreadCount, - }, + // Sharing replaces Team Sync: the Team page stays only for a project still in a team. + ...(hasTeamPage(state, project.id) + ? [ + { + id: "team" as const, + label: "Team", + icon: Users, + count: state.team?.find((item) => item.projectId === project.id) + ?.unreadCount, + }, + ] + : []), { id: "docs", label: "Docs", icon: BookOpen }, ]; const projectGroups = new Map(); @@ -616,9 +638,16 @@ export function App() { const shared = state.team?.find((room) => room.projectId === item.id); const label = shared ? (shared.teamName ?? "Shared preview projects") - : "Personal projects"; + : isSharedHere(state, item.id) + ? SHARED_GROUP + : "Personal projects"; projectGroups.set(label, [...(projectGroups.get(label) ?? []), item]); } + // Shared projects come last, so those not on this computer yet follow them. + const switcherGroups = [...projectGroups].sort( + ([left], [right]) => + Number(left === SHARED_GROUP) - Number(right === SHARED_GROUP), + ); return (
@@ -672,7 +701,10 @@ export function App() { {projectMenu && (
- {[...projectGroups].map(([group, items]) => ( + {switcherGroups.map(([group, items]) => (
{group} {items.map((item) => ( - +
+ + { + setSelectedId(null); + setProjectMenu(false); + void sharing.refresh(); + }} + /> +
))}
))} + { + setSelectedId(null); + setView("board"); + setProjectMenu(false); + void sharing.refresh(); + }} + />
-
)}
@@ -844,6 +892,22 @@ export function App() { > + {sharing.overview && + offersSharing(sharing.overview, project, state) && ( + { + setSettingsSection("account"); + setDialog("settings"); + }} + /> + )} )} + {view === "board" && + !project.path && + isSharedHere(state, project.id) && ( +
+ setFolderSetupOpen((value) => !value)} + /> + {folderSetupOpen && ( + setView("workers")} + onInsights={() => setView("insights")} + /> + )} +
+ )} {view === "docs" && ( }> ) : null; }; + // Someone else asked to continue a worker run here: it waits for this person. + const asked = (task: WorkItem) => { + const count = task.sharedAsks?.length ?? 0; + return count > 0 ? ( + + + {count} to allow + + ) : null; + }; const lanes: BoardGroup[] = groups ?? stages.map((stage) => ({ @@ -601,6 +615,7 @@ function BoardContent({
{queued(task)} + {asked(task)} {discussion(task)} {task.stage === "done" ? ( diff --git a/src/components/ConversationMessage.tsx b/src/components/ConversationMessage.tsx index a0c95bb..90b0a41 100644 --- a/src/components/ConversationMessage.tsx +++ b/src/components/ConversationMessage.tsx @@ -83,13 +83,14 @@ const ConversationMessage = memo(
- void openLink(href)} - comments={comments} - onOpenReference={(reference, id) => { - const note = comments.find((c) => c.id === id); - if (note) void focusComment(note); - else if (reference.path) void openLink(reference.path); - }} - /> + {othersRun && shared ? ( + void openLink(href)} + /> + ) : ( + void openLink(href)} + comments={comments} + onOpenReference={(reference, id) => { + const note = comments.find((c) => c.id === id); + if (note) void focusComment(note); + else if (reference.path) void openLink(reference.path); + }} + /> + )} {!remote && health.available && task.run.state === "running" && ( @@ -873,6 +948,13 @@ export function WorkDetail({

)} {!remote && startupProgress} + {!!localTask.sharedAsks?.length && ( + + )} {pendingInputs.length > 0 && (
{pendingInputs.map((request) => ( @@ -880,137 +962,159 @@ export function WorkDetail({ ))}
)} -
- {attachedComments.length > 0 && ( -
- {attachedComments.map((id) => { - const note = comments.find((c) => c.id === id); - return note ? ( - - - {note.reference.name} ·{" "} - {reviewLocation(note.reference)} - + {othersRun && ( +

+ {onlyItsOwnerContinues(othersRun)} + +

+ )} + {!othersRun && ( + <> +
+ {attachedComments.length > 0 && ( +
+ {attachedComments.map((id) => { + const note = comments.find((c) => c.id === id); + return note ? ( + + + {note.reference.name} ·{" "} + {reviewLocation(note.reference)} + + + ) : null; + })} +
+ )} +