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/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/app.ts b/runtime/app.ts index 2223095..ce9bdd1 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -80,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"; @@ -154,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); @@ -206,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; @@ -231,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 = () => { @@ -359,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(), @@ -717,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 && @@ -747,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()); @@ -1259,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)), @@ -1403,6 +1483,8 @@ export async function createRuntime( handoffAttribution: state().settings.handoffAttribution, }; await changed(); + // New sharing addresses: boards on the old service stop, boards on the new one start. + void sharing?.syncBoards(); return dshProfileChanged ? revalidateDshOverrides() : store.runtime(); }, ); @@ -1461,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 ); }); @@ -1556,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; @@ -1624,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( @@ -1631,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."); @@ -1678,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); @@ -1891,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 ( @@ -1947,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), @@ -2047,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/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/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/local.ts b/runtime/local.ts index 681d5e7..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"); 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/workers.ts b/runtime/workers.ts index da6d1f6..013055b 100644 --- a/runtime/workers.ts +++ b/runtime/workers.ts @@ -67,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 { @@ -1104,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" + 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/memtrace-engine.json b/scripts/memtrace-engine.json index 2966150..f0c4dd1 100644 --- a/scripts/memtrace-engine.json +++ b/scripts/memtrace-engine.json @@ -1,64 +1,64 @@ { "bundles": { "macos-aarch64": { - "id": "3a87836d4-beta.1", + "id": "3a87836d4-beta.1-devid-9817c16c6d02", "engineVersion": "1.2.22", "purpose": "memcode-engine-beta", "platform": "macos", "arch": "aarch64", - "url": "https://d12b8r6xagt10r.cloudfront.net/releases/memtrace-engine/3a87836d4/3a87836d4-beta.1-macos-aarch64-e8b0565600d5a587.zip", - "sha256": "e8b0565600d5a587c0085295890361644f49e133c9401c2f8aacc70dc75a2138", - "bytes": 75170025, + "url": "https://d12b8r6xagt10r.cloudfront.net/releases/memtrace-engine/3a87836d4/3a87836d4-beta.1-devid-9817c16c6d02-macos-aarch64-9817c16c6d027910.zip", + "sha256": "9817c16c6d0279102286678d13f03e17b74430f5fd09f4f626806213a18eb2d9", + "bytes": 73925969, "files": [ { "name": "BETA-USAGE.txt", - "bytes": 1221, - "sha256": "391cf5739b15b518f5bb0c7957b606926538c2f879d09abb49019d6b0cc645a1" + "sha256": "391cf5739b15b518f5bb0c7957b606926538c2f879d09abb49019d6b0cc645a1", + "bytes": 1221 }, { "name": "ENGINE-PROVENANCE.json", - "bytes": 2101, - "sha256": "448db11cc05729b97d715af3c59e8a68da11fa9f0e7562d0c4d94a80592db527" + "sha256": "448db11cc05729b97d715af3c59e8a68da11fa9f0e7562d0c4d94a80592db527", + "bytes": 2101 }, { "name": "LICENSE", - "bytes": 3049, - "sha256": "a312a2fe4dc83634aa35f115a1bff571a1bdc1e3a4ed604a5be7941b566ea3a6" + "sha256": "a312a2fe4dc83634aa35f115a1bff571a1bdc1e3a4ed604a5be7941b566ea3a6", + "bytes": 3049 }, { "name": "LICENSE-MEMDB.txt", - "bytes": 1737, - "sha256": "5bb41bad8c267da43e09fbb35a7acba43864aafb40e3f91a0a880795e7c7cef5" + "sha256": "5bb41bad8c267da43e09fbb35a7acba43864aafb40e3f91a0a880795e7c7cef5", + "bytes": 1737 }, { "name": "NOTICE", - "bytes": 781, - "sha256": "ac6d438a063247a369d154722f4c8c210baa3e79d55dcf2686a5b9b1efaa981e" + "sha256": "ac6d438a063247a369d154722f4c8c210baa3e79d55dcf2686a5b9b1efaa981e", + "bytes": 781 }, { "name": "THIRD-PARTY-NOTICES.txt", - "bytes": 10819, - "sha256": "8b6b2440f7b60a79adfb1026eb790db6f91c469d606c5cab2777d30750a32f5a" + "sha256": "8b6b2440f7b60a79adfb1026eb790db6f91c469d606c5cab2777d30750a32f5a", + "bytes": 10819 }, { "name": "memcore-server", - "bytes": 22549504, - "sha256": "f9fb7bbadab6526a00dac61e4d44784bb2fe782ca6694bd46c42b807d4b2cf7e" + "sha256": "9a9aa7e5a6e33d0edb0995b94af4ba00bcdb961073a0099aff1aaad8118d0c0a", + "bytes": 22436656 }, { "name": "memcortex-daemon", - "bytes": 41364992, - "sha256": "adb7537676d08432b5b9c44116257b2c5b386d6d79594c5303b41f4ecb4ad019" + "sha256": "6dd791842c7555ee8a78c24aadd0abefcdce57b3533af97d887c44ebc8bad73c", + "bytes": 41142752 }, { "name": "memcortex-mcp", - "bytes": 10590496, - "sha256": "d184cac00b6fbe2ca27375b092265239d7d5073c937ba6454ace2f234d1412ec" + "sha256": "ea82f90e5fa70c6a29fb98f27307d264a33a3336342a969872b113d96180be30", + "bytes": 10547184 }, { "name": "memtrace", - "bytes": 168177984, - "sha256": "e6bb42a38cae134273951487f92ea95e6d9efb8c570a90f1ed2da2b99d429c0f" + "sha256": "d2ab42bc20a3613574dc61b2dde9af87d0933522414360ec70dad2d203a767ea", + "bytes": 167218464 } ] }, 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 b271670..f006ee8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2350,7 +2350,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memcode" -version = "0.4.0-beta.20" +version = "0.4.0-beta.21" dependencies = [ "base64 0.23.1", "block2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9fea334..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" 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(