diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5509fbf..8bde9bc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -654,7 +654,7 @@ jobs:
# on this repository can publish an update that every installed client downloads and runs. That is the
# same capability as the signing key, reached through a different door — and docs/adr/0011 rule 1 puts
# that capability on a machine which is not a runner, because a workflow secret is held by everyone who
-# can change a workflow file. See docs/adr/0012-desktop-distribution-and-updates.md.
+# can change a workflow file. See docs/adr/0013-desktop-distribution-and-updates.md.
#
# What cuts a release is scripts/release-windows.ps1, run by a person. What this file does is prove the
# thing still builds and packages, which is the same division of labour the android job above already
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 3c0d23d..0a150ed 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -160,7 +160,7 @@
The update feed this is pointed at is the project's own forge and never a DodoSSH deployment.
That is ADR 0011 rule 2, and it is the reason the repository URL in VelopackUpdateSource is a
constant rather than a setting: an operator who could answer the update check could pin a
- chosen user to a known-vulnerable build. See docs/adr/0012-desktop-distribution-and-updates.md.
+ chosen user to a known-vulnerable build. See docs/adr/0013-desktop-distribution-and-updates.md.
-->
diff --git a/README.md b/README.md
index 924da91..3435b71 100644
--- a/README.md
+++ b/README.md
@@ -118,7 +118,7 @@ signing certificate, so Windows SmartScreen shows *"Windows protected your PC"*
installer; **More info → Run anyway** gets past it. That is the honest state of things rather than something
to click through blindly — it is a statement that Microsoft has not seen this file before, and it will stop
appearing when the project buys a certificate.
-[ADR 0012](docs/adr/0012-desktop-distribution-and-updates.md) says what that costs and when it happens. The
+[ADR 0013](docs/adr/0013-desktop-distribution-and-updates.md) says what that costs and when it happens. The
warning is once per person: updates from inside the application do not raise it.
**Updates.** The client checks the project's release page every six hours, downloads a newer build in the
@@ -140,7 +140,7 @@ you want the machine to genuinely forget everything — an uninstall is not a si
this machine's device key from your account.
Cutting a release is `scripts/release-windows.ps1`, run by a person on a Windows machine. Deliberately not a
-CI job; ADR 0012 decision 3 explains why, and it is not only that the runners are Linux.
+CI job; ADR 0013 decision 3 explains why, and it is not only that the runners are Linux.
## Running it
@@ -377,14 +377,75 @@ Six limits, stated rather than discovered:
into it that is not there.
Items are filed into one vault at a time, and which one is asked at the moment the item is made. **A host's
-editor has its own picker**, beside the name, because that is the decision that cannot be undone: the two
-vaults are encrypted under different keys, so moving an item afterwards means deleting it and typing it
-again — and the picker is therefore absent when you edit an existing host rather than present and refusing.
-Keys, passwords and buckets take theirs from a standing "new items go to" picker on the Keychain screen.
+editor has its own picker**, beside the name, because it is the decision on that form that decides who can
+read the host. It is absent when you edit an existing one rather than present and refusing, and that is not
+because the host is stuck: **a host can be moved to another vault** — "Move to another vault…" in the detail
+pane's menu on the desktop, MOVE beside EDIT on the phone. It is a separate act because it is not a save.
+The two vaults are encrypted under different keys, so a move is a re-seal into one and a tombstone in the
+other; the host gets a new id, and **its group and its tags stay behind**, because both are items of the
+vault it is leaving. A picker inside the form would do all of that as a side effect of correcting a port.
+What a move cannot do is reach a machine that has already synced the host, which is the same limit
+everything else about revocation has. Keys, passwords and buckets take theirs from a standing "new items go
+to" picker on the Keychain screen and cannot be moved yet.
+
+**A group can be moved too, and it takes its contents with it** — "Move to another vault…" on the group
+card's right-click menu, beside Open, Edit and Delete, which is the whole of what can be done to a group on
+the desktop. That is the desktop only, because the phone draws groups as headings in the host list and has
+never had a way to delete or move one. It is the same re-seal
+and tombstone underneath, applied to every item involved: the group, the groups nested inside it, and every
+host filed under any of them, each taking a new id in the destination. Moving less than that was never
+coherent — the machines and the child groups are items of the vault the group is leaving, so a group that
+travelled alone would leave half a shelf behind. What stays is the group it was itself nested under, which
+belongs to the old vault, so it arrives at the top level; the hosts' tags stay for the same reason. Keys and
+passwords are kept, because those genuinely resolve across vaults, and the sentence afterwards names any
+that are now outside the destination.
+
+**Deleting a group asks what should become of the hosts under it.** The default answer keeps them: the
+reference is cleared and they move to UNGROUPED. Ticking the box deletes them with it. Both answers are a
+change — the deletion used to leave the hosts holding an id that no longer resolved, which looked the same
+and cost nothing, and stopped being the right shape once the deletion could take them with it. A group with
+nothing filed under it is not asked. Whichever answer is given, the groups nested inside take the deleted
+group's place in the tree rather than being orphaned to the top level.
Both default to your personal vault and neither moves on its own, because an item put in a shared vault is
visible to everybody holding that vault's key. Choosing a vault in the host editor also decides which groups
it can be filed under: a group is an item like any other and lives in exactly one vault.
+### Changes that do not wait
+
+A client holds a WebSocket open to the server — `GET /api/v1/events`, subprotocol
+`dodossh.events.v1` — and the server sends a line down it whenever something you can read has moved. The
+client's answer is the same delta pull it would have run on its timer, only now rather than in up to a
+minute. Two things you can see: an edit somebody else makes appears while you are looking at the list, and
+a vault shared with you turns up as soon as they share it.
+
+**What is on that socket is a notice, not your data.** A frame says which vault changed and how far its
+change log has got, and nothing else: no item, no ciphertext, not even which item it was. That is the
+decision the rest of this rests on, and it is deliberate twice over — the server has nothing else it
+*could* send, and keeping it that way means there is still exactly one path that applies a change to your
+keychain, so the socket can be wrong or absent without anything being applied incorrectly.
+
+**Polling is still there and is still what guarantees a pass.** The minute timer is unchanged. A network
+that eats WebSockets, a server with `Events:Enabled` off, an older server, a proxy that will not upgrade, a
+notice dropped because your machine was too slow to read it — every one of those leaves you with exactly
+what this product did before the socket existed. Nothing is reachable only this way, and nothing is
+supposed to become so.
+
+Three limits are worth knowing rather than discovering:
+
+- **One node.** Fan-out is in-process, so a deployment running more than one API replica only pushes for
+ writes that its own replica handled. The rest arrive on the timer. The seam for a PostgreSQL
+ `LISTEN`/`NOTIFY` backplane is in place and is not implemented, because an untested backplane would be
+ worse than a documented gap.
+- **The socket does not outlive your access token.** It is closed at the token's expiry and the client
+ reconnects with a fresh one, which is a gap you will not see. That, plus re-reading your vault list every
+ few minutes, is what bounds how long a withdrawn grant can keep producing notices — and what it bounds is
+ *metadata*, because reading a vault needs a key the server has never held.
+- **You are told about your own writes.** Your client pushed, so it has already pulled; the extra pass finds
+ nothing. Notices are coalesced over a quarter of a second so that a burst is one pass rather than a dozen.
+
+The reasoning, including why this is a WebSocket rather than server-sent events and where a shared terminal
+session will attach to it, is in [ADR 0012](docs/adr/0012-realtime-push.md).
+
### The Android head
`src/DodoSSH.Client.Android` is a phone-first head that shares every view model with the desktop one — the
@@ -632,6 +693,16 @@ keychain plus a terminal — and the spike that gates all of it.
than to a shell that never opens. Given a walk that had to be cycle-safe anyway, refusing to nest bought
nothing.
+ Membership living on the host has one further consequence, and it took two goes to settle. Deleting a
+ group could not clear it without rewriting every host under the heading, so at first it did not: the hosts
+ kept an id that resolved to nothing and turned up under UNGROUPED, which reads identically and costs no
+ writes. That held until the deletion had to be able to take the hosts *with* it — a group is sometimes a
+ heading being tidied away and sometimes a project that has been decommissioned, and nothing in the code can
+ tell which. Once a deletion knows which hosts it means, leaving them naming something that has gone is a
+ state kept for no reason, so both answers now write: N deletions, or N hosts with the reference cleared.
+ The dangling case still has to be survived everywhere it is read, because a group deleted on *another*
+ machine arrives exactly that way.
+
Inserting a snippet types it at the prompt and stops. Pressing Enter is a per-snippet decision, off by
default, and the reason is worth stating: a terminal is one input stream with no notion of being at a
prompt — the remote may be in an editor, or at a password prompt with the echo off — so this client cannot
@@ -658,6 +729,20 @@ keychain plus a terminal — and the spike that gates all of it.
directories, an interrupted **upload** starts again rather than resuming (an object cannot be written from
the middle), and a rename is a copy and a delete rather than one atomic operation. Downloads do resume — a
ranged GET is part of the protocol, which is the one place a bucket beats SFTP.
+
+ *Realtime done:* a WebSocket the client holds open, over which the server says which vault has moved so a
+ pull happens now rather than within the minute. What crosses it is a notice and never an item, which is
+ what keeps one code path applying changes and makes a dropped socket cost latency and nothing else — the
+ timer is unchanged and is still the guarantee. Two limits are stated rather than implied: fan-out is
+ in-process, so a multi-replica deployment falls back to the timer for writes another replica handled, and
+ a socket is closed at its access token's expiry rather than outliving the credential that authorised it.
+ See [Changes that do not wait](#changes-that-do-not-wait) and
+ [ADR 0012](docs/adr/0012-realtime-push.md).
+
+ It is also the transport a **shared terminal session** will use — one person's shell, watched or driven by
+ somebody else. Nothing of that exists yet, and ADR 0012 records the one decision made early so it need not
+ be renegotiated: session data will be binary frames on this same socket, because base64 in a JSON envelope
+ is the wrong shape for the one payload here that is continuous rather than occasional.
- **M3 — shared vaults**, sharing, ACLs. *Done.* Membership with roles, a public-key directory, the
append-only key log served for clients to verify against, shared vaults, and vault key grants
wrapped by a client and stored opaquely by the server. `VaultAccessService` now resolves team
@@ -681,10 +766,12 @@ keychain plus a terminal — and the spike that gates all of it.
the rotation is re-sealed as it is pushed, so nothing reaches the server under a superseded key at all.
See [ADR 0010](docs/adr/0010-vault-key-rotation.md).
- **A vault shared with you arrives on the next synchronisation pass**, within the minute, with no sign-in
- and nothing to press. There is no push channel, so each pass asks the server which vaults this account can
- reach before syncing the ones it already knows — which is also how a vault that has been deleted, or one
- whose grant was withdrawn, stops being listed.
+ **A vault shared with you arrives at once**, with no sign-in and nothing to press. Each pass asks the
+ server which vaults this account can reach before syncing the ones it already knows — which is also how a
+ vault that has been deleted, or one whose grant was withdrawn, stops being listed — and the server now
+ says so the moment somebody wraps a key to you rather than leaving it for the next pass. Without a
+ reachable socket that becomes "within the minute", which is what it always was; see
+ [Changes that do not wait](#changes-that-do-not-wait).
**Ownership transfer is here, and it is one write rather than two.** The member you name becomes owner
and you become an admin, in a single transaction — because ownership is sole, so promoting first leaves
@@ -708,7 +795,7 @@ keychain plus a terminal — and the spike that gates all of it.
the first time the API has reported a true `serverVersion`. Releases are cut by a person rather than by
CI: the token that writes a release is, for an updater that trusts its feed, the same capability as the
signing key, which [ADR 0011](docs/adr/0011-android-distribution.md) rule 1 keeps off runners. See
- [ADR 0012](docs/adr/0012-desktop-distribution-and-updates.md), and
+ [ADR 0013](docs/adr/0013-desktop-distribution-and-updates.md), and
[Installing on Windows](#installing-on-windows) for what a user sees.
Still to do here: signing (the first release is unsigned, and the trigger for buying a certificate is the
diff --git a/docs/adr/0003-sync-protocol.md b/docs/adr/0003-sync-protocol.md
index cdfbda5..05443d8 100644
--- a/docs/adr/0003-sync-protocol.md
+++ b/docs/adr/0003-sync-protocol.md
@@ -58,7 +58,11 @@ the Npgsql connection string** — the default; do not enable multiplexing.
- One place enforces revision, change-log and ACL invariants. That halves both the endpoint
count and the authorization surface, which is the main reason for the single write path.
- Delta pull makes frequent polling cheap, so multi-device feels live; push notification over
- SSE or the existing WebSocket can layer on with polling as the fallback.
+ SSE or the existing WebSocket can layer on with polling as the fallback. **That has since been
+ built — see [ADR 0012](0012-realtime-push.md)** — and nothing in this ADR changed to accommodate
+ it. The socket carries a notice naming a vault and a sequence, whose answer is the delta pull
+ above, so there is still exactly one path that applies a change; and polling is still what
+ guarantees a pass rather than a legacy route kept for old clients.
- Conflict resolution is entirely client-side. The client retains a `BaseCiphertext` common
ancestor and performs a field-level three-way merge for structured items, or creates a
visible conflicted copy for opaque ones. **It must never silently drop a key or a host.**
diff --git a/docs/adr/0012-realtime-push.md b/docs/adr/0012-realtime-push.md
new file mode 100644
index 0000000..2bb7b61
--- /dev/null
+++ b/docs/adr/0012-realtime-push.md
@@ -0,0 +1,167 @@
+# ADR 0012 — A WebSocket that carries notices, not data
+
+- Status: accepted
+- Date: 2026-08-04
+
+## Context
+
+[ADR 0003](0003-sync-protocol.md) built a delta pull that is cheap enough to run on a timer, and
+the client does: one pass a minute. That is the difference between a colleague's change appearing
+"soon" and appearing *now*, and it shows up in three places that are not equally forgivable.
+
+- **A vault shared with you** arrives on the next pass. `AdmitNewVaultsAsync` says so in its own
+ remarks — "the recipient is handed nothing — there is no push channel" — and the README repeats
+ it. Sharing works and looks broken.
+- **Two people editing one keychain** see each other up to a minute late, which is long enough to
+ make the same edit twice and produce a conflict that nobody needed to have.
+- **A revoked grant** keeps serving a client that has not noticed yet, for up to a pass.
+
+Shortening the interval is the obvious answer and the wrong one: it costs a request per client per
+interval whether or not anything happened, and it does not converge on *immediate* — it converges
+on a busier server that is still late.
+
+There is also a second thing coming that this decision has to not preclude. The intended feature is
+a **shared terminal session** — one person's shell, watched or driven by another, TeamViewer-shaped.
+That is bidirectional, continuous, and latency-sensitive in a way a keychain notice is not.
+
+## Decision
+
+### One WebSocket per signed-in client, at `GET /api/v1/events`
+
+Subprotocol `dodossh.events.v1`. The client opens it after unlock and keeps it open; the server
+sends a notice whenever something the client can read has changed.
+
+**Not SSE.** Server-sent events would carry today's notices perfectly well and would be less code.
+It is one-directional, so the shared-session feature would need a second mechanism next to it, and
+then two transports would need reconnection, authorization and lifetime rules that agree. The cost
+of a WebSocket over SSE is small; the cost of two transports is not.
+
+**Not SignalR.** It brings hub protocol negotiation, its own serialisation and transport fallbacks,
+none of which are wanted here: `DodoSSH.Contracts` and its source-generated serialiser are "the
+actual contract between the two sides", and a second wire format alongside it is exactly the silent
+drift `Setup/Json.cs` records having already cost this project once.
+
+### The notice carries no ciphertext
+
+A `vault.changed` frame is `{ kind, vaultId, sequence }` and nothing else. The client's answer to it
+is the pull it would have done on the timer anyway.
+
+This is the load-bearing decision, and it is worth being explicit about why the tempting alternative
+is refused. Pushing the changed items themselves would save a round trip and would fork the code
+path that applies a change into two — one that arrives by pull and one that arrives by socket — with
+the cursor, the merge and the tombstone rules duplicated across both. ADR 0003 put every mutation
+through one write path for exactly that reason; this keeps every *read* on one path for the same
+one. The socket decides *when* to sync. It never decides *what* a vault contains.
+
+It also means a dropped notice is harmless, which is what lets everything below be simple.
+
+### Polling stays, and is the fallback rather than a legacy path
+
+The one-minute pass is unchanged. The socket makes it *early*; it does not make it *necessary*. A
+client on a network that eats WebSockets, an older client, a server that has the feature off, a
+notice dropped under backpressure, a second API replica that did not see the write — every one of
+those degrades to what the product does today, which is correct and up to a minute late.
+
+Nothing may be reachable only by socket. That is a rule about future features, not an observation
+about this one.
+
+### Authorization: the bearer token on the upgrade, not a ticket
+
+[ADR 0004](0004-relay-authorization.md) gives the relay a two-step ticket so its WebSocket carries
+no API authority. This one goes the other way and takes the ordinary bearer JWT on the upgrade
+request, which is an ordinary authenticated HTTP request. The difference is not inconsistency:
+
+- The relay's socket is a **byte pipe to a third party**, and its whole authorization decision —
+ which host, which IPs, which port — is made *before* the socket opens and never revisited. It is
+ also the extraction seam for a standalone relay process that must not hold ACL code.
+- This socket is a **view of the caller's own vault list**, and it has to keep answering "what may
+ this account read" for as long as it is open. It needs the full ACL context, in-process, for the
+ life of the connection. A ticket would carry that context in a token instead, and it would be
+ wrong the moment the account's access changed.
+
+A long-lived connection authorised by a short-lived token is the problem this creates, and it is met
+head-on rather than ignored:
+
+1. **The socket does not outlive the token.** The `exp` claim is read at accept, and the connection
+ is closed with `4401` when it passes. The client reconnects with a fresh token; that is a
+ sub-second gap in a channel whose failure mode is already "poll instead".
+2. **The vault set is re-resolved periodically** (`Events:AccessRefreshInterval`, default five
+ minutes) as well as on the changes that are known to affect it. A withdrawn grant therefore stops
+ producing notices within that window at the latest, and immediately in the ordinary case.
+
+Both are bounds on **metadata** — the fact that a vault changed and roughly when — because that is
+all a notice contains. Nobody's ciphertext is behind this socket, and a client that stayed subscribed
+one interval too long could still not read a byte of it: reading requires a vault key grant, which
+this server has never held.
+
+### The frames
+
+Text frames, JSON, `DodoSshJsonContext`. Server to client:
+
+| kind | meaning |
+| --- | --- |
+| `hello` | accepted; carries the heartbeat interval and the vault count subscribed |
+| `vault.changed` | `vaultId` moved to `sequence`; pull it |
+| `vaults.changed` | the set of vaults this account can reach is different; re-read it |
+| `ping` | heartbeat; the client answers `pong` |
+
+Client to server: `ping`, answered with `pong`. Nothing else — subscription is decided by the server
+from the caller's access, not asked for by the client, because a client that could ask to subscribe
+to a vault id is a client that can probe for vault ids.
+
+`kind` is a **string**, not an enum, and that is deliberate. `UseStringEnumConverter` throws on a
+value it does not know, so a newer server sending a kind an older client has never heard of would
+not add an unknown frame — it would break that client's socket entirely. A string is ignored
+instead, which is what makes the table above extensible. `ProblemCodes` is the same shape for the
+same reason.
+
+### Where the shared session will attach
+
+The socket is the seam, and one thing about it is chosen now so that it need not be renegotiated
+later: **session data will be binary frames on this same connection, not JSON on the table above.**
+Terminal output base64'd into a JSON envelope would cost a third of the bandwidth for nothing, on
+the one payload here that is continuous rather than occasional. Control — offer, accept, resize,
+end — is JSON like everything else.
+
+That is as far as this ADR goes. Two questions are open and are not being answered by implication:
+whether a shared session's bytes go through the API at all or peer-to-peer past it, and what
+end-to-end encryption means when the second party is watching a stream rather than holding a key.
+Both are ADR 0001 questions and deserve their own decision. What this one buys is that they will not
+also be transport questions.
+
+## Consequences
+
+- **Fan-out is in-process, and the deployment is therefore single-node for this feature.** Every
+ connection is held by the node that accepted it; a write handled by another node produces no
+ notice on this one. `IVaultEventPublisher` is the seam a backplane implements — PostgreSQL
+ `LISTEN`/`NOTIFY` needs no infrastructure this stack does not already run — and it is deliberately
+ **not implemented**, because an untested backplane is worse than a documented gap. Multiple API
+ replicas do not break: they degrade to polling, which is the state before this ADR. `/api/v1/meta`
+ advertises `events` so a client knows which it is getting.
+- **Per-connection queues are bounded and drop the oldest.** A notice is "pull vault X, which is at
+ least at sequence N", so the newest is strictly more useful than the one it displaces and the
+ client's answer is identical either way. A slow reader costs itself latency, never the publisher's
+ progress — the publish path never blocks and never awaits a socket.
+- **The publish happens after the transaction commits**, outside the advisory lock ADR 0003 takes.
+ A notice sent from inside it would name a sequence a reader cannot yet see, and would hold the
+ per-vault write lock across a socket write.
+- **A client is notified of its own writes.** It pushed, so it already pulled; the extra pass finds
+ nothing. The client coalesces notices over a short window rather than the server suppressing an
+ echo, because suppressing it correctly needs a per-*device* identity on the socket and the same
+ user's other machines must still be told.
+- **Connections are capped** per user and per node (`Events:MaxConnectionsPerUser`,
+ `Events:MaxConnectionsTotal`). A socket is cheap but not free, and an unbounded count of them is a
+ denial of service that authenticates first.
+- The feature can be turned off entirely (`Events:Enabled`). A deployment behind a proxy that will
+ not upgrade should say so rather than have every client discover it by failing.
+
+### Rejected
+
+- **Shorter polling.** Cheaper to build, converges on a busier server that is still late.
+- **Long polling.** No new transport and genuinely immediate, but it holds a request thread and a
+ connection per client for the same money as a WebSocket while offering none of the bidirectionality
+ the shared session needs.
+- **Pushing the changed items down the socket.** Saves a round trip; forks the apply path in two. See
+ above.
+- **Client-chosen subscriptions.** A `subscribe(vaultId)` frame is an existence oracle for vault ids,
+ which is the disclosure `SyncPullEndpoint` answers 404 rather than 403 to avoid.
diff --git a/docs/adr/0012-desktop-distribution-and-updates.md b/docs/adr/0013-desktop-distribution-and-updates.md
similarity index 99%
rename from docs/adr/0012-desktop-distribution-and-updates.md
rename to docs/adr/0013-desktop-distribution-and-updates.md
index 1fc6a24..11c22ab 100644
--- a/docs/adr/0012-desktop-distribution-and-updates.md
+++ b/docs/adr/0013-desktop-distribution-and-updates.md
@@ -1,4 +1,4 @@
-# ADR 0012 — Distributing the desktop client, and letting it replace itself
+# ADR 0013 — Distributing the desktop client, and letting it replace itself
- Status: accepted
- Date: 2026-08-04
@@ -43,7 +43,7 @@ not degrade the product, it would remove the terminal.
Velopack's path was checked against that and reintroduces nothing: `Setup.exe` is an ordinary Win32
executable that unpacks a directory and creates shortcuts, there is no package manifest and no package
-identity, and the process therefore stays an ordinary desktop process. Manual check 15.4 is what would
+identity, and the process therefore stays an ordinary desktop process. Manual check 16.4 is what would
notice if that ever changed, because it connects a real shell from the installed build.
### 2. The pack id is `DodoSSH.Desktop`, and it is irreversible
diff --git a/docs/design-import-gaps.md b/docs/design-import-gaps.md
index 9cf65d9..131b6c3 100644
--- a/docs/design-import-gaps.md
+++ b/docs/design-import-gaps.md
@@ -157,7 +157,7 @@ the chrome, hosts and terminals, file transfer, the vault, teams, and preference
> | **Add Telnet**, and **Serial** in the toolbar | Omitted. `ISshConnection` is the only transport there is. This is also why the card subtitle's `ssh` is a constant today rather than a reading — it is stated in `HostRowViewModel.Summary`, which is the one place in this interface where a constant is printed on purpose. |
> | **+ SSH ID, Certificate, FIDO2** | Omitted. `IDENTITIES` and `CERTIFICATES` have been on this document's list since the first import — neither is even a reserved `SyncEntityType` — and there is no security-key path anywhere in the SSH layer. One control offering three item types that do not exist. |
> | The **Backspace / Default** row | Omitted. It is a terminal setting, and the client has no preferences store and no frame to carry one to the renderer — see the Preferences section. It would be a control whose value could not survive the window closing. |
-> | The **chevron beside the vault name** | The name alone, on the pane about an existing host: an item cannot be moved between vaults, because the two are encrypted under different keys and moving one is a delete and a retype. The half of the question that *does* have an answer — where a new host goes — is asked in the host editor, as a picker beside the name; keys, passwords and buckets take theirs from the keychain screen's standing picker instead. |
+> | The **chevron beside the vault name** | The name alone, and the move behind the pane's ⋯ menu instead. A host *can* now be moved between vaults, so the gap is no longer that there is nothing to offer — it is that a chevron on a subtitle implies an edit, and this is not one: the two vaults are encrypted under different keys, so it is a re-seal into one and a tombstone in the other, the host takes a new id, and its group and tags stay behind. A control that implied "just change this field" would be describing something else. Where a *new* host goes is still asked in the host editor, as a picker beside the name. A group moves too, from its card's right-click menu, and takes its nested groups and every host filed under them; keys, passwords and buckets take theirs from the keychain screen's standing picker and cannot be moved yet. |
> | **Show more ⌄** | Not drawn as a disclosure. What it would hide — notes, the relay switch, forgetting the host key — is in the editor, one press away, and a second fold inside a pane that already scrolls is a second place for a field to be missing from. |
> | **Port Forwarding** in the sidebar | Nothing, for the third time in this document. |
> | The host grid's toolbar avatar, share and tag-filter controls | Omitted, as in v3 and for the same reasons. |
@@ -307,7 +307,7 @@ caption buttons and window title drawn on top of the application's own — two s
| Tag chips (`nginx`, `eu`, `pg16`) | client-domain | A tag item type, and a way to put one on a host. | **Shipped.** `Tag = 5` is a live item kind and `HostSecret.TagIds` names them, merged per tag so two people tagging one host both keep theirs — which is what `HostTag = 6` was going to buy, so it stays reserved and unused. Chips are drawn on host rows on both heads and toggled in the host editor, which also creates one inline; renaming and deleting are a TAGS category on the keychain screen. The filter box still searches name, address and notes only — a chip is read rather than typed. |
| Groups `PRODUCTION` / `STAGING` / `PERSONAL` | client-domain | A host-group item type (`HostGroup = 4`, reserved) or a group field on `HostSecret`. | **Shipped**, as both: `VaultHostGroup` is a synced item kind and `HostSecret.GroupId` names one. A group carries a `ParentId` and the defaults its hosts inherit, and the two heads draw the nesting differently on purpose. The desktop is a grid of cards holding one level at a time, the way a directory pane holds one directory; the phone has no room for a row of cards, so it flattens the whole tree into one heading per group in label order with no indentation. A keychain with no groups renders exactly as it did before on both — one flat list, no headings and no cards. |
| Group badge `TEAM·PLATFORM` | server | **Built in M3.** | The vault's name on each row, and the personal vault ordered first. Not the team's name: two of a team's vaults would then carry the same badge and the badge would be naming the wrong thing. Distinct from the groups above, and deliberately so — a group is a shelf the user chose, a vault is who can read the item. |
-| Groups on a **team's** hosts | client-domain | A vault id on each group row for rename and delete, and a way to tell two vaults' identically-named groups apart in a list with one heading per group. | **Half shipped, and the half that shipped had to.** Every readable vault's groups are now read into the resolution map, because a group lends a port, a username and a binding — so a host whose group went unread would silently dial 22 as nobody while the machine is on 2222 as `deploy`. A missing heading is cosmetic; a missing port is a connection to the wrong place. The editable list is still the active vault's alone, so a group a teammate made has no card and no heading and cannot be renamed from here. A host filed into one is drawn at the outermost level of the desktop's grid and under UNGROUPED on the phone — reachable either way, which is the point — with the chip on its card still naming the group, because the label is resolved through the wide map while the level is decided from the narrow list. |
+| Groups on a **team's** hosts | client-domain | A vault id on each group row for rename and delete, and a way to tell two vaults' identically-named groups apart in a list with one heading per group. | **Shipped, and it is what makes a shared vault an arrangement rather than a heap.** Both halves are paid for: the row carries the vault it came out of, so rename and delete go back to it, and the vault's name is drawn beside the group's on the desktop's cards and the phone's headings wherever the session holds more than one — which is what lets two `production` groups sit side by side. The group editor asks which vault a new group goes into, on the terms the host editor's picker set: while adding only, hidden at one writable vault, and never offered afterwards, because the two are encrypted under different keys. The parent picker is that vault's alone, for the reason the host editor's group picker is — a parent in another vault is a level half the key holders cannot resolve. Dragging a host card onto a group card in another vault is refused with the reason, rather than filing it under an id nobody in its own vault can read. The resolution map stays wider than the list and still spans hidden vaults: a group lends a port, a username and a binding, so a host whose group went unread would silently dial 22 as nobody while the machine is on 2222 as `deploy`. |
| Per-host status dot, three colours | client-ssh | The amber state would mean "reachable but not connected", and nothing here ever probes a host. | Two states, both real: green when a terminal is open on that host, grey when not. |
| `· ⤷ bastion-eu` in the host subtitle | client-ssh | **Jump hosts are data-only.** `HostSecret.JumpHostIds` is a `JumpChain` that is stored, encrypted, synced and three-way merged — and nothing reads it at connect time. `SshConnectionRequest` carries one host. | Omitted. The stored chain is preserved untouched by every edit. |
| `SPLIT ⌘D` and side-by-side panes | client-ssh + ui | The renderer stacks panes and shows one (`terminal.css`: `.pane { position:absolute; inset:0; display:none }`). Tiling needs a real pane geometry and a splitter. | Omitted. Tabs ship instead, over the same one-WebView multiplexing. |
diff --git a/docs/manual-checks.md b/docs/manual-checks.md
index 09deb57..a8f5109 100644
--- a/docs/manual-checks.md
+++ b/docs/manual-checks.md
@@ -324,7 +324,8 @@ phone's, whose list has no room for a row of group cards and draws the whole tre
host filed, the grid says so in a sentence rather than sitting empty.
**Then press a group card once.** It is marked as chosen and **nothing else happens** — the grid is still the
-level it was, and EDIT and DELETE now aim at that group. **Then double-press it.** The group opens: its hosts
+level it was, and no buttons appear beside the GROUPS heading: editing and deleting a group are on the card's
+own right-click menu, which is 7.9. **Then double-press it.** The group opens: its hosts
are the grid, the trail above the cards reads `ALL HOSTS › ›`, each card carrying the group's name as
an accent chip, and the card grid shows what is *inside* that group rather than every group in the keychain.
Pressing ALL HOSTS goes back to the outermost level.
@@ -347,9 +348,9 @@ Make two groups and file one under the other with the parent picker in the group
**Pass:** only the outer group has a card to start with. Double-press it and the inner one is the only card
shown, with the trail reading `ALL HOSTS › ›`. Double-press that, and the cards disappear entirely —
-it has nothing inside it — while the trail, EDIT and DELETE stay: with no card selected the two buttons act
-on the group the trail ends with, so a group with nothing in it can still be renamed after being opened.
-Pressing the **middle** crumb goes back one level rather than all the way out.
+it has nothing inside it — while the trail stays. Pressing the **middle** crumb goes back one level rather
+than all the way out, which is also how a group with nothing inside it is renamed: back out to the level
+where it has a card, and right-click that.
**Failure means:** cards for groups that are not at this level is `VisibleGroups` having been bound past —
the flat `Groups` is the phone's and the lookups'. A group that cannot be reached at all is worse and is the
@@ -370,13 +371,35 @@ takes only the group that is open.
### 3.3 Deleting a group with hosts in it
-Select a group with hosts and press DELETE.
+Right-click a group with hosts in it and choose **Delete…**. Do it twice: once leaving the tick alone, and
+once — on another group — ticking it.
-**Pass:** the question names how many hosts are filed under it and says they stay. Agreeing removes the
-group; the hosts lose their chip and are otherwise unchanged.
+**Pass:** the question names how many hosts are filed under it, says they stay and move to UNGROUPED, and
+offers a tick that would delete them as well. The tick starts clear, and it starts clear again on the next
+group even if it was set on the last one. Left clear, agreeing removes the group and the hosts stay, without
+a chip and otherwise unchanged. Ticked, the hosts go with it — and only the hosts that were filed under that
+group. A group with nothing under it is asked no second question and shows no tick.
-**Failure means:** if the hosts vanish, the delete is rewriting host payloads, which it must not — see
-`HostGroupRepository`.
+**Failure means:** a tick that carries from one question to the next is the reset in `OnPendingDeletionChanged`
+having gone, and it deletes machines on the strength of a decision about a different group. Hosts that keep
+the chip after an unticked delete are the unfiling not happening: they still name a group that is gone, which
+is what this used to do on purpose and no longer should.
+
+### 3.3a Moving a group to another vault · **needs a second vault**
+
+Build `outer › inner` with a host in `inner`, all in your personal vault, then right-click **outer** and
+choose **Move to another vault…**. Pick the shared vault and press MOVE.
+
+**Pass:** the panel says what travels and what does not before you press anything. Afterwards all three items
+carry the destination's badge, `inner` is still inside `outer` and the host is still inside `inner` — every
+one of them under an id it did not have a moment ago. The sentence names the vault, the counts, and the fact
+that the group now sits at the top level if it was nested. Nothing is left behind in the vault it came from.
+
+**Failure means:** a host under UNGROUPED in the destination is the group id having been carried across
+rather than remapped — the ids are the destination's making, so every reference has to be rewritten as its
+target lands. Anything still in the source vault is a partial move, which is survivable by design but should
+not happen with the network up: the groups are written top-down and the hosts last, so an interruption leaves
+hosts behind and never a shelf with nothing on it.
### 3.4 A group deleted on another machine · **needs two machines**
@@ -795,6 +818,17 @@ With host A selected, right-click host B and choose Delete.
wrong machine. `HostGridTests` covers both halves headlessly, so this is a confirmation that a real popup
behaves as the headless one did.
+**And the same on the group cards above.** Open a group, then right-click a card inside it and choose
+Delete.
+
+**Pass:** the question names the **card**, not the group that is open — and Open on that menu goes into the
+card, rather than back out to ALL HOSTS. Right-clicking the space around the group cards opens no menu.
+
+**Failure means:** the menu is reading `GroupTarget`'s fallback, which is the group whose contents are on
+screen rather than the card the pointer is on. This menu is the only way to edit or delete a group on the
+desktop — there are no buttons beside the GROUPS heading any more — so a menu aimed wrongly is the whole of
+the mistake.
+
### 7.10 Clicking a host in the palette connects
Ctrl+K, then click a result with the mouse rather than pressing Enter.
@@ -1279,6 +1313,31 @@ rather than a broken role.
under the people who share it is an administrative act reached without the role for it. The server refuses
it too — this is the interface not offering what the server would turn down.
+### 12.10 A group made in a shared vault arrives as a group, not as a heap · **needs two accounts**
+
+1. As Alice, on HOSTS, press + NEW GROUP, choose the shared vault in the editor's VAULT picker, name it
+ `production`, and give it a default port and username.
+2. Add two hosts to the same shared vault and file them under it.
+3. Make a second group called `production` in the **personal** vault.
+4. Sync, then look at Bob's machine after his own sync.
+
+**Pass on Alice's:** the two cards are told apart by the vault name printed under each — same name, two
+folders — and on the phone the two headings carry the same badge. Opening either shows only its own hosts.
+Dragging one of the shared vault's host cards onto the personal `production` card is **refused with a
+sentence naming both vaults**, and the host stays where it was.
+
+**Pass on Bob's:** the group is a card and a heading on his machine too, with the hosts inside it, and the
+port and username they dial are the ones Alice typed into the group rather than 22 and his own account. He
+can rename it, and the rename comes back to Alice rather than arriving as a second group in his personal
+vault.
+
+**Failure means:** a group that reaches Bob as UNGROUPED hosts is the resolution map having gone narrow
+again — cosmetic on its own, except that the port and the username go with it, so his terminal dials the
+wrong place. A rename of his that turns up as a new group in his own vault is the editor writing to the
+active vault rather than to the row's, which forks the shelf and leaves Alice's untouched. Two identical
+cards with no vault under them means one of them is a folder somebody outside the team can read, and
+nothing on screen says which.
+
---
## Phase 13 — Unlocking the phone with a fingerprint
@@ -1466,9 +1525,88 @@ delivery survives the failure because it is held against the transfer rather tha
dropped on the failure. An error saying the staged file is missing is the copy having been deleted at the
stop, which is what `QueueDeliveredDownload` documents it does not do.
+## Phase 15 — Changes that arrive without a timer
+
+The socket is covered by tests on both sides: the endpoint suite opens a real one against a real
+`TestServer` and proves a push produces a notice, that another account's push does not, and that a frame
+carries no ciphertext; the shell suite proves a notice wakes the synchronisation loop long before the
+minute. What none of that can reach is **the network in between**, and that is where this feature is most
+likely to fail: a reverse proxy that will not upgrade, one that drops an idle socket without telling either
+end, a corporate middlebox, a phone moving between Wi-Fi and mobile data. Every one of those looks the same
+from inside a test host, which has no proxy and no radio.
+
+The pass condition throughout is *two* things, and the second matters as much as the first: it arrives
+quickly, **and** it still arrives when the socket is gone. A build where the timer had stopped working would
+pass every "it was fast" check here and fail nobody until somebody's proxy changed.
+
+### 15.1 A colleague's edit appears while you are looking at it
+
+Two accounts sharing a vault, both unlocked, both on the Hosts screen. On the first machine, rename a host
+in the shared vault and save.
+
+**Pass:** the second machine's list shows the new name within a second or two, with nothing pressed and no
+screen flicker — the row updates, the selection does not move, and the status line is not repainted with a
+sync report.
+
+**Failure means:** nothing within a minute, then the new name, is the socket not being established at all —
+that is the timer doing its job, which is the correct fallback and not the feature. Check `/api/v1/meta`
+lists `events`, then whether the proxy in front of the API forwards `Upgrade` and `Connection`. A list that
+never updates at all is a synchronisation failure and has nothing to do with this phase.
+
+### 15.2 A vault shared with you turns up as it is shared
+
+The second account signed in and unlocked, sitting on the VAULTS screen. From the first, add them to a team
+and press SHARE KEY.
+
+**Pass:** the vault appears in their list within a second or two of the key being wrapped, and reads as
+waiting for a key until the share, then as readable.
+
+**Failure means:** the vault appearing only on the minute is the `vaults.changed` notice not being published
+or not being followed. Both the membership add and the grant publish one; if the membership arrives promptly
+and the key does not, the grant path is the one to look at.
+
+### 15.3 It still works with the socket taken away
+
+On the second machine, block the WebSocket — the simplest way is a proxy rule rejecting the upgrade, or
+setting `Events:Enabled` to `false` on the server and restarting it.
+
+**Pass:** everything above still happens, within the minute rather than within seconds. Nothing on the
+screen says anything is wrong, because nothing is: no error, no OFFLINE badge, no repeated status message.
+The Sync button still works and still reports.
+
+**Failure means:** an error message, a titlebar claiming to be offline, or a status line that repaints with
+a socket failure is the client treating an absent push channel as a fault. It is not one — the timer is the
+guarantee and the socket is the optimisation, and a user with a strict proxy must never be told their
+keychain is broken.
+
+### 15.4 A laptop that slept comes back on its own
+
+With the second machine idle and connected, close the lid for a few minutes — or disable Wi-Fi for two
+minutes and re-enable it. Then make a change on the first machine.
+
+**Pass:** the change arrives quickly again, without the vault having been locked or the application
+restarted. The reconnection is invisible.
+
+**Failure means:** changes that arrive only on the timer from then on are the stream having given up after
+its socket died — the reconnection loop is what should make that impossible, and a client that reconnects
+once and not twice is the specific defect its tests exist to catch. Changes that never arrive again, timer
+included, are a different and worse bug in the synchronisation loop rather than in the socket.
+
+### 15.5 An expiring token does not end the push
+
+This one needs a short access-token lifetime in the identity provider — the dev realm's Keycloak client can
+be set to a couple of minutes. Leave a machine unlocked and idle for longer than that, then make a change
+elsewhere.
+
+**Pass:** the change still arrives quickly. The socket is closed by the server at the token's expiry and the
+client reconnects with a fresh one, which should be invisible.
+
+**Failure means:** notices stopping at roughly the token's lifetime is the reconnection not asking for a new
+token — it would be dialling with the spent one and being closed again immediately. A burst of reconnection
+attempts in the server log is the same defect seen from the other end.
---
-## Phase 15 — Installing the desktop client, and being updated by it
+## Phase 16 — Installing the desktop client, and being updated by it
Nothing in this phase is reachable by a test, and not for the usual reason. There is no installed
application in CI, no `%LOCALAPPDATA%` worth inspecting, and the update path only exists across two builds
@@ -1478,12 +1616,12 @@ of the view model against a fake channel, and pins the one promise that matters
(`AReadyUpdate_IsNeverAppliedOnItsOwn`); `UpdateBannerTests` measures the banner at the window's minimum
width. Neither can install anything.
-Walk it once per release, and in order — 15.6 onwards needs 15.1 to have happened.
+Walk it once per release, and in order — 16.6 onwards needs 16.1 to have happened.
Run `pwsh -File scripts/release-windows.ps1` first. It stops after packing, on purpose, so that everything
below happens before anything reaches a user.
-### 15.1 The installer needs no administrator, and lands beside the vault rather than on it · **the one that would destroy data**
+### 16.1 The installer needs no administrator, and lands beside the vault rather than on it · **the one that would destroy data**
Run `Releases\DodoSSH.Desktop-win-Setup.exe` from an ordinary account. Then look at `%LOCALAPPDATA%`.
@@ -1493,9 +1631,9 @@ reading **DodoSSH**; and `%LOCALAPPDATA%\DodoSSH` either absent (a fresh machine
**Failure means:** a UAC prompt is a per-machine install, which is not what was designed. Anything written
into `%LOCALAPPDATA%\DodoSSH` is the pack id having drifted back to `DodoSSH`, and that is the serious one —
the uninstaller removes its whole install root, so it would take the vault cache and the outbox with it.
-See [ADR 0012](adr/0012-desktop-distribution-and-updates.md) decision 2.
+See [ADR 0013](adr/0013-desktop-distribution-and-updates.md) decision 2.
-### 15.2 The installed path is short, measured rather than assumed
+### 16.2 The installed path is short, measured rather than assumed
```powershell
"$env:LOCALAPPDATA\DodoSSH.Desktop\current\DodoSSH.exe".Length
@@ -1507,7 +1645,7 @@ See [ADR 0012](adr/0012-desktop-distribution-and-updates.md) decision 2.
`CO_E_SERVER_EXEC_FAILURE` and name nothing — see the long-path entry in `platform-flags.md`, which is the
reason this check is a number rather than a shrug.
-### 15.3 The window opens and carries its own icon
+### 16.3 The window opens and carries its own icon
**Pass:** the Start-menu shortcut launches it, and the taskbar and Alt-Tab show the dodo mark rather than a
generic icon.
@@ -1515,7 +1653,7 @@ generic icon.
**Failure means:** `--icon` or `ApplicationIcon` did not survive packaging. Cosmetic, and the first thing
anybody notices.
-### 15.4 A terminal connects from the installed build · **the one that would catch an AppContainer**
+### 16.4 A terminal connects from the installed build · **the one that would catch an AppContainer**
Sign in, unlock, open a shell against a real host, and type.
@@ -1527,7 +1665,7 @@ WebView2 in an AppContainer where the loopback data plane cannot connect. That i
out for, and this is the check that would find it in the Velopack path. `RendererTimeout` is where the
fifteen seconds comes from.
-### 15.5 The version on screen is the version that was built
+### 16.5 The version on screen is the version that was built
Right-click `DodoSSH.exe` → Properties → Details, and open PREFERENCES → UPDATES.
@@ -1539,7 +1677,7 @@ dropped from a checkout. `1.0.0.0` is somebody having wired the app manifest's i
version to the real one. A version on screen that differs from the file properties means the two are being
read from different places, which is the thing having one number was for.
-### 15.6 A second release produces a delta, not only a full package
+### 16.6 A second release produces a delta, not only a full package
Tag `v0.1.1` and run the script again.
@@ -1551,7 +1689,7 @@ previous release did not come down, so every user is about to fetch a ~60 MB ful
change. The
script warns rather than failing when that is legitimate, which is the first release only.
-### 15.7 The update arrives, and the restart lands in it · **the whole point of the work**
+### 16.7 The update arrives, and the restart lands in it · **the whole point of the work**
With v0.1.0 installed and running, a vault unlocked, a host change made, and **a terminal open**, publish
v0.1.1 (`-Upload`). Then press CHECK NOW on PREFERENCES rather than waiting six hours.
@@ -1566,11 +1704,11 @@ intact.
and reports the client up to date forever. A banner sliced at the terminal's left edge is the occlusion rule
having been broken, and the fallback is to move the offer into the titlebar instead. Coming back as 0.1.0 is
the swap having been blocked, usually by a process still holding a file under `current\`. Being asked to
-enrol again means the profile directory did not survive, which is 15.1's failure arriving late.
+enrol again means the profile directory did not survive, which is 16.1's failure arriving late.
-### 15.8 The first connect after an update is not a cold start
+### 16.8 The first connect after an update is not a cold start
-Immediately after 15.7, connect to a host.
+Immediately after 16.7, connect to a host.
**Pass:** the terminal appears about as quickly as it did before the update.
@@ -1578,7 +1716,7 @@ Immediately after 15.7, connect to a host.
see the entry in `platform-flags.md`. Slow but working, so it gets dismissed as a fluke unless somebody is
looking for it, which is why it is a numbered check rather than a note.
-### 15.9 Uninstalling removes the application and leaves the vault · **the data-loss check**
+### 16.9 Uninstalling removes the application and leaves the vault · **the data-loss check**
Settings → Apps → DodoSSH → Uninstall.
@@ -1587,5 +1725,5 @@ Settings → Apps → DodoSSH → Uninstall.
is wrong. Reinstalling then asks for the passphrase rather than for a server.
**Failure means:** the cache going with the application is the pack-id collision, and whoever ran this has
-lost their offline unlock and any change that was still in the outbox. That is the failure ADR 0012
-decision 2 exists to prevent, and it is why 15.1 checks the same thing from the other end.
+lost their offline unlock and any change that was still in the outbox. That is the failure ADR 0013
+decision 2 exists to prevent, and it is why 16.1 checks the same thing from the other end.
diff --git a/docs/platform-flags.md b/docs/platform-flags.md
index 2e17cac..005d9ae 100644
--- a/docs/platform-flags.md
+++ b/docs/platform-flags.md
@@ -225,7 +225,7 @@ suspect.
40-character corporate username adds 35 of them back. The shipped installer is not at risk. Two things
would reopen it and neither is in the plan: a self-extracting single-file publish, whose native libraries
land under a hashed temp path, and `%LOCALAPPDATA%` folder-redirected to a deep UNC path in a domain.
-Manual check 15.2 measures it on the real machine rather than trusting this paragraph.
+Manual check 16.2 measures it on the real machine rather than trusting this paragraph.
**WebView2's user data folder must be kept out of the install directory.** It defaults to a directory
beside the host executable, which under Velopack is inside `current\` — and `current\` is *replaced* by
@@ -233,7 +233,7 @@ every update. Left alone, the browser profile would be destroyed on each one, so
every update would pay a cold WebView2 start: a fresh user-data directory and a new process tree, which is
the slow path `RendererTimeout`'s fifteen seconds was sized for, arriving at the exact moment somebody is
most ready to believe the update broke the terminal. `Program.Main` sets `WEBVIEW2_USER_DATA_FOLDER` to
-`%LOCALAPPDATA%\DodoSSH\WebView2` — under the profile directory, which Velopack never touches. Check 15.8
+`%LOCALAPPDATA%\DodoSSH\WebView2` — under the profile directory, which Velopack never touches. Check 16.8
is what would notice it regressing, and it is worth having because the symptom is "slow but working", which
gets dismissed as a fluke.
@@ -243,7 +243,7 @@ gets dismissed as a fluke.
choice — would have made the uninstaller delete the vault cache and the outbox of changes not yet pushed,
silently, which is the thing the application will not do without a counted confirmation. The pack id is
`DodoSSH.Desktop` for that reason and no other; `--packTitle` supplies the name people see, so nothing is
-lost. Do not "tidy" it. See [ADR 0012](adr/0012-desktop-distribution-and-updates.md) and check 15.9.
+lost. Do not "tidy" it. See [ADR 0013](adr/0013-desktop-distribution-and-updates.md) and check 16.9.
**The Windows app manifest must declare a `supportedOS` list.** Without it the process reports a
downlevel Windows version and Avalonia's native control host fails outright — *"Unable to create child
@@ -358,7 +358,7 @@ for Windows/macOS/AppImage; Flatpak and deb/rpm defer updates to the package man
reintroduce the thing MSIX was ruled out for. `Setup.exe` is an ordinary Win32 executable that unpacks a
directory under `%LOCALAPPDATA%` and creates shortcuts — there is no `AppxManifest`, no package identity,
no `runFullTrust`, no elevation and no execution alias, so the process stays an ordinary desktop process
-and WebView2 stays out of an AppContainer. That is reasoning, not measurement; manual check 15.4 is the
+and WebView2 stays out of an AppContainer. That is reasoning, not measurement; manual check 16.4 is the
measurement, because if a package identity ever did appear the symptom would be the terminal hanging and
then reporting the WebView2 message after fifteen seconds, which reads like a broken runtime rather than
like packaging.
diff --git a/scripts/release-windows.ps1 b/scripts/release-windows.ps1
index dda0d95..3035328 100644
--- a/scripts/release-windows.ps1
+++ b/scripts/release-windows.ps1
@@ -5,14 +5,14 @@
.DESCRIPTION
Run by a person, on a Windows machine that is not a CI runner. That is not an accident of tooling —
docs/adr/0011-android-distribution.md rule 1 puts the capability to ship somebody a build on a machine
- which is not a runner, and docs/adr/0012-desktop-distribution-and-updates.md explains why the token that
+ which is not a runner, and docs/adr/0013-desktop-distribution-and-updates.md explains why the token that
writes a Gitea release is that capability: Velopack clients trust their feed and do not verify a package
signature when they apply it, so whoever can write a release can ship an update every install runs.
Two phases, and the split is the design rather than a convenience.
1. Without -Upload: builds, packs, and stops. Nothing has left this machine.
- Install the Setup.exe it names, and walk Phase 15 of docs/manual-checks.md.
+ Install the Setup.exe it names, and walk Phase 16 of docs/manual-checks.md.
2. With -Upload: asks for the forge token and publishes what phase 1 produced. It does not rebuild,
so the bytes that reach users are the bytes that were installed and checked.
@@ -116,7 +116,7 @@ try {
}
Write-Host "About to publish the contents of $ReleasesDir to $RepoUrl as $tag."
- Write-Host 'Only do this once you have installed it and walked Phase 15 of docs/manual-checks.md.'
+ Write-Host 'Only do this once you have installed it and walked Phase 16 of docs/manual-checks.md.'
# Read-Host -AsSecureString so the token is never echoed and never lands in the shell's history.
$secure = Read-Host -Prompt 'Gitea token (write:repository)' -AsSecureString
@@ -252,7 +252,7 @@ try {
# run, once per user — Mark-of-the-Web is applied by the browser that downloads Setup.exe, so in-app
# updates, which this application fetches itself and applies from a local file, never trip it.
#
- # This is the one line that changes when a certificate is bought. See ADR 0012 for what it costs and
+ # This is the one line that changes when a certificate is bought. See ADR 0013 for what it costs and
# what the trigger for buying one is.
& dotnet vpk pack `
--packId $PackId `
@@ -274,7 +274,7 @@ try {
Format-Table -AutoSize
Write-Host 'Next:'
- Write-Host " 1. Install the Setup executable above and walk Phase 15 of docs/manual-checks.md."
+ Write-Host " 1. Install the Setup executable above and walk Phase 16 of docs/manual-checks.md."
Write-Host ' 2. Then: pwsh -File scripts/release-windows.ps1 -Upload'
}
finally {
diff --git a/src/DodoSSH.Api/Features/Events/EventsEndpoint.cs b/src/DodoSSH.Api/Features/Events/EventsEndpoint.cs
new file mode 100644
index 0000000..46246b2
--- /dev/null
+++ b/src/DodoSSH.Api/Features/Events/EventsEndpoint.cs
@@ -0,0 +1,533 @@
+using System.Collections.Frozen;
+using System.Globalization;
+using System.Net.WebSockets;
+using System.Security.Claims;
+using System.Text.Json;
+using DodoSSH.Api.Authorization;
+using DodoSSH.Api.Setup;
+using DodoSSH.Contracts;
+using DodoSSH.Domain.Authorization;
+using FastEndpoints;
+using Microsoft.Extensions.Options;
+
+namespace DodoSSH.Api.Features.Events;
+
+///
+/// The socket that says "pull now" so a client does not have to wait for its timer.
+///
+///
+///
+/// Everything this endpoint sends is a notice. It never carries an item, a payload or a
+/// cursor: the client's answer to a notice is the delta pull it would have run on its own anyway, so
+/// there is exactly one code path that applies a change and this is not it. See ADR 0012 for why
+/// pushing the items themselves is refused.
+///
+///
+/// The bearer token authorises the upgrade, unlike the relay's ticket in ADR 0004. The relay's socket
+/// is a byte pipe whose whole authorization decision is made before it opens; this one is a view of
+/// the caller's own vault list and has to keep answering "what may this account read" for as long as
+/// it is held. Its two bounds on that — the token's own expiry, and a periodic re-resolve — are in
+/// .
+///
+///
+internal sealed class VaultEventsEndpoint(
+ IServiceScopeFactory scopes,
+ VaultEventHub hub,
+ IOptions options,
+ TimeProvider clock,
+ IHostApplicationLifetime lifetime,
+ ILogger logger)
+ : EndpointWithoutRequest
+{
+ ///
+ /// The largest message this endpoint will read from a client.
+ ///
+ ///
+ /// A client sends nothing but ping, so the cap is three orders of magnitude of headroom and
+ /// still small enough that a hostile client cannot make the server buffer anything worth having.
+ ///
+ private const int MaxInboundFrameBytes = 4 * 1024;
+
+ /// How long to wait for the close handshake before dropping the socket.
+ private static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(5);
+
+ ///
+ public override void Configure()
+ {
+ Get(VaultEvents.Path);
+
+ // Enrolled, matching sync. A caller with no identity key holds no vault key either, so every
+ // notice this socket could send is about ciphertext they cannot read.
+ Policies(Auth.EnrolledPolicy);
+
+ Description(b => b
+ .WithName("VaultEvents")
+ .WithSummary("Pushes a notice when a vault the caller can read has changed.")
+ .WithTags("Events"));
+ }
+
+ ///
+ public override async Task HandleAsync(CancellationToken ct)
+ {
+ if (await RefusedAsync().ConfigureAwait(false))
+ {
+ return;
+ }
+
+ var (userId, vaults) = await ResolveAccessAsync(ct).ConfigureAwait(false);
+
+ // Admitted before the upgrade so a refusal costs nothing, but answered *through* the socket
+ // rather than as an HTTP status: a constrained WebSocket client cannot read the status of a
+ // failed upgrade, and "you have too many open" is precisely the case where the client needs
+ // to know to back off rather than retry. Same reasoning as ADR 0004 on request headers.
+ var connection = hub.TryAdmit(userId, vaults);
+
+ try
+ {
+ using var socket = await HttpContext.WebSockets
+ .AcceptWebSocketAsync(new WebSocketAcceptContext { SubProtocol = VaultEvents.SubProtocol })
+ .ConfigureAwait(false);
+
+ if (connection is null)
+ {
+ await CloseAsync(
+ socket,
+ new Closure(
+ VaultEvents.TooManyConnectionsCloseCode, "Too many open event sockets."))
+ .ConfigureAwait(false);
+
+ return;
+ }
+
+ await PumpAsync(socket, connection, ct).ConfigureAwait(false);
+ }
+ finally
+ {
+ // Inside a try that starts *before* the upgrade, because an accept that throws — a client
+ // that abandoned the handshake — would otherwise leave an admitted connection in the hub
+ // for the life of the process, counting against this account's cap and taking a slot from
+ // the sockets that did open.
+ if (connection is not null)
+ {
+ hub.Remove(connection);
+ }
+ }
+ }
+
+ ///
+ /// Answers the requests that are not an event socket at all, as ordinary HTTP.
+ ///
+ /// Whether a response was sent and the handler should stop.
+ ///
+ /// All three answers are problem documents rather than bare statuses, because each one has a
+ /// different remedy and a client that cannot tell them apart would retry the two that will never
+ /// succeed. Answered before the upgrade, so a caller that got the handshake wrong reads why in a
+ /// body rather than inferring it from a socket that closed.
+ ///
+ private async Task RefusedAsync()
+ {
+ if (!options.Value.Enabled)
+ {
+ // 404 rather than 501: the feature is absent from this deployment, and /api/v1/meta does
+ // not advertise it. A client that dialled anyway keeps polling, which is correct.
+ await Send.ResultAsync(Problems.Coded(
+ StatusCodes.Status404NotFound,
+ ProblemCodes.EventsUnavailable,
+ "This server does not push vault changes. Synchronise on a timer instead; "
+ + "GET /api/v1/meta lists the features it does offer."))
+ .ConfigureAwait(false);
+
+ return true;
+ }
+
+ if (!HttpContext.WebSockets.IsWebSocketRequest)
+ {
+ await Send.ResultAsync(Problems.Coded(
+ StatusCodes.Status400BadRequest,
+ ProblemCodes.MalformedRequest,
+ "This endpoint is a WebSocket. Send an upgrade request offering the "
+ + $"'{VaultEvents.SubProtocol}' subprotocol."))
+ .ConfigureAwait(false);
+
+ return true;
+ }
+
+ // The subprotocol is this API's version negotiation for the socket, so an upgrade that does
+ // not offer it is refused rather than accepted and answered in a dialect the caller may not
+ // read. See VaultEvents.SubProtocol.
+ if (!HttpContext.WebSockets.WebSocketRequestedProtocols
+ .Contains(VaultEvents.SubProtocol, StringComparer.Ordinal))
+ {
+ await Send.ResultAsync(Problems.Coded(
+ StatusCodes.Status400BadRequest,
+ ProblemCodes.MalformedRequest,
+ $"This server speaks '{VaultEvents.SubProtocol}', which the upgrade request did "
+ + "not offer."))
+ .ConfigureAwait(false);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ ///
+ /// Reads who the caller is and which vaults they may follow, in a scope of its own.
+ ///
+ ///
+ /// A fresh scope, disposed at once, rather than services injected into this endpoint — which is
+ /// the lesson ADR 0004 records paying for on the relay. This handler runs for as long as the
+ /// socket is open, so anything scoped it held would be a DbContext alive for hours, and a
+ /// few hundred of those exhaust the connection pool. The database is touched here and in
+ /// , briefly, and nowhere else.
+ ///
+ private async Task<(Guid UserId, FrozenSet Vaults)> ResolveAccessAsync(
+ CancellationToken cancellationToken)
+ {
+ var scope = scopes.CreateAsyncScope();
+ await using var _ = scope.ConfigureAwait(false);
+
+ var currentUser = scope.ServiceProvider.GetRequiredService();
+ var vaultAccess = scope.ServiceProvider.GetRequiredService();
+
+ var user = await currentUser.GetOrProvisionAsync(cancellationToken).ConfigureAwait(false);
+
+ return (user.Id, await ReachableAsync(vaultAccess, user.Id, cancellationToken).ConfigureAwait(false));
+ }
+
+ private static async Task> ReachableAsync(
+ IVaultAccessService vaultAccess,
+ Guid userId,
+ CancellationToken cancellationToken)
+ {
+ var accessible = await vaultAccess.ListAsync(userId, cancellationToken).ConfigureAwait(false);
+
+ return accessible
+ .Where(access => access.Vault is not null
+ && access.Permissions.HasFlag(PermissionFlags.Read))
+ .Select(access => access.Vault!.Id)
+ .ToFrozenSet();
+ }
+
+ /// Runs the socket until something ends it, then closes it politely.
+ ///
+ /// Three loops rather than one: reading a socket and writing to it are independent waits, and the
+ /// clock is a third. They are joined by and then all
+ /// awaited before the close is written, because a close frame racing a notice frame is a protocol
+ /// violation that presents as a client dropping its connection for no visible reason.
+ ///
+ private async Task PumpAsync(
+ WebSocket socket,
+ VaultEventConnection connection,
+ CancellationToken requestAborted)
+ {
+ var settings = options.Value;
+
+ using var pump = CancellationTokenSource.CreateLinkedTokenSource(
+ requestAborted, lifetime.ApplicationStopping);
+
+ var closure = new Closure(
+ (int)WebSocketCloseStatus.NormalClosure, string.Empty);
+
+ connection.TryEnqueue(new VaultEvent(
+ VaultEventKinds.Hello,
+ ServerTime: clock.GetUtcNow(),
+ HeartbeatSeconds: (int)settings.HeartbeatInterval.TotalSeconds,
+ VaultCount: connection.VaultCount));
+
+ var sending = SendAsync(socket, connection, pump.Token);
+ var receiving = ReceiveAsync(socket, connection, pump.Token);
+ var minding = MindAsync(connection, closure, pump.Token);
+
+ await Task.WhenAny(sending, receiving, minding).ConfigureAwait(false);
+
+ await pump.CancelAsync().ConfigureAwait(false);
+
+ // Nothing may still be mid-send when the close frame goes out.
+ await Task.WhenAll(Settled(sending), Settled(receiving), Settled(minding)).ConfigureAwait(false);
+
+ if (lifetime.ApplicationStopping.IsCancellationRequested)
+ {
+ // 1001 "going away", so a client knows to reconnect immediately rather than treating a
+ // rolling deployment as a server that has broken.
+ closure.Set((int)WebSocketCloseStatus.EndpointUnavailable, "The server is shutting down.");
+ }
+
+ EventsLog.ClosingConnection(logger, connection.UserId, closure.Reason);
+
+ await CloseAsync(socket, closure).ConfigureAwait(false);
+ }
+
+ ///
+ /// Writes queued frames to the socket, one at a time.
+ ///
+ ///
+ /// The only writer, which is what makes concurrent sends impossible without a lock: the
+ /// heartbeat and the pong both go into the same queue rather than to the socket. A WebSocket
+ /// permits one send at a time and faults permanently on a second, so this is not a tidiness
+ /// preference.
+ ///
+ private async Task SendAsync(
+ WebSocket socket,
+ VaultEventConnection connection,
+ CancellationToken cancellationToken)
+ {
+ await foreach (var frame in connection.Outbound
+ .ReadAllAsync(cancellationToken)
+ .ConfigureAwait(false))
+ {
+ // Re-resolved before the notice is forwarded, not after: the client's answer to this frame
+ // is to re-read its vault list, and the point of a newly shared vault is that the *next*
+ // change to it produces a notice too. A socket that forwarded first would not follow the
+ // new vault until its next periodic refresh.
+ if (string.Equals(frame.Kind, VaultEventKinds.VaultsChanged, StringComparison.Ordinal))
+ {
+ await RefreshAsync(connection, cancellationToken).ConfigureAwait(false);
+ }
+
+ var bytes = JsonSerializer.SerializeToUtf8Bytes(frame, DodoSshJsonContext.Default.VaultEvent);
+
+ await socket
+ .SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, cancellationToken)
+ .ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// Reads what the client sends, which in this version is heartbeats and a close.
+ ///
+ ///
+ /// A client cannot ask to follow a vault, and that is deliberate rather than unfinished: a
+ /// subscribe(vaultId) frame is an existence oracle for vault ids, which is the disclosure
+ /// SyncPullEndpoint answers 404 rather than 403 to avoid. Subscription is decided from the
+ /// caller's access and nothing else.
+ ///
+ private static async Task ReceiveAsync(
+ WebSocket socket,
+ VaultEventConnection connection,
+ CancellationToken cancellationToken)
+ {
+ var buffer = new byte[MaxInboundFrameBytes];
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ var received = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
+
+ if (received.MessageType == WebSocketMessageType.Close)
+ {
+ return;
+ }
+
+ // Oversized, or split across frames. Nothing this protocol sends is either, so the client
+ // is broken or probing; ending the socket is cheaper than reassembling for it.
+ if (!received.EndOfMessage)
+ {
+ return;
+ }
+
+ // Binary is unused in v1 and skipped rather than refused, because ADR 0012 reserves it for
+ // shared-session data — an older server meeting a newer client must ignore those, not
+ // close on them.
+ if (received.MessageType != WebSocketMessageType.Text)
+ {
+ continue;
+ }
+
+ if (Kind(buffer.AsSpan(0, received.Count)) is VaultEventKinds.Ping)
+ {
+ connection.TryEnqueue(new VaultEvent(VaultEventKinds.Pong));
+ }
+ }
+ }
+
+ ///
+ /// Reads a frame's kind, or null if it is not one this server understands.
+ ///
+ ///
+ /// A frame that will not parse is skipped rather than closing the socket. This is a control
+ /// channel whose failure mode is "the client polls instead", so tolerating a frame from a newer
+ /// client costs nothing and refusing one costs that client its push for the whole session.
+ ///
+ private static string? Kind(ReadOnlySpan utf8)
+ {
+ try
+ {
+ return JsonSerializer.Deserialize(utf8, DodoSshJsonContext.Default.VaultEvent)?.Kind;
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ ///
+ /// Keeps the heartbeat going, the vault set current, and the socket inside its token's lifetime.
+ ///
+ ///
+ ///
+ /// The deadline is the earlier of the access token's exp and a hard cap on how long any one
+ /// socket may live. Closing on expiry is what keeps a long-lived connection from outliving the
+ /// short-lived credential that authorised it; the client answers by reconnecting with a fresh
+ /// token, which is a sub-second gap in a channel that degrades to polling anyway.
+ ///
+ ///
+ /// The wait is the shorter of the heartbeat and the time left, so the deadline is met to within a
+ /// tick rather than to within a heartbeat.
+ ///
+ ///
+ private async Task MindAsync(
+ VaultEventConnection connection,
+ Closure closure,
+ CancellationToken cancellationToken)
+ {
+ var settings = options.Value;
+ var started = clock.GetUtcNow();
+
+ var deadline = TokenExpiry() is { } expiry && expiry < started + settings.MaxConnectionDuration
+ ? (Expiry: expiry, ForToken: true)
+ : (Expiry: started + settings.MaxConnectionDuration, ForToken: false);
+
+ var refreshed = started;
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ var now = clock.GetUtcNow();
+ var remaining = deadline.Expiry - now;
+
+ if (remaining <= TimeSpan.Zero)
+ {
+ closure.Set(
+ deadline.ForToken
+ ? VaultEvents.TokenExpiredCloseCode
+ : (int)WebSocketCloseStatus.NormalClosure,
+ deadline.ForToken
+ ? "The access token has expired. Reconnect with a fresh one."
+ : "This connection reached its maximum lifetime.");
+
+ return;
+ }
+
+ var wait = settings.HeartbeatInterval < remaining ? settings.HeartbeatInterval : remaining;
+
+ await Task.Delay(wait, clock, cancellationToken).ConfigureAwait(false);
+
+ now = clock.GetUtcNow();
+
+ if (now - refreshed >= settings.AccessRefreshInterval)
+ {
+ // The backstop for a grant withdrawn while this socket was open. What it bounds is
+ // metadata — that a vault changed — because that is all a notice carries and reading
+ // the vault still needs a key this server has never held. See ADR 0012.
+ await RefreshAsync(connection, cancellationToken).ConfigureAwait(false);
+ refreshed = now;
+ }
+
+ connection.TryEnqueue(new VaultEvent(VaultEventKinds.Ping, ServerTime: now));
+ }
+ }
+
+ /// Re-reads which vaults this socket may follow.
+ ///
+ /// A failure is logged and swallowed. The alternative is dropping a working socket because one
+ /// database call timed out, which would trade an occasionally stale vault set for an outage.
+ ///
+ private async Task RefreshAsync(VaultEventConnection connection, CancellationToken cancellationToken)
+ {
+ try
+ {
+ var scope = scopes.CreateAsyncScope();
+ await using var _ = scope.ConfigureAwait(false);
+
+ var vaultAccess = scope.ServiceProvider.GetRequiredService();
+
+ connection.Resubscribe(
+ await ReachableAsync(vaultAccess, connection.UserId, cancellationToken)
+ .ConfigureAwait(false));
+ }
+ catch (OperationCanceledException)
+ {
+ // The socket is closing.
+ }
+ catch (Exception exception) when (exception is not OutOfMemoryException)
+ {
+ EventsLog.AccessRefreshFailed(logger, connection.UserId, exception);
+ }
+ }
+
+ ///
+ /// MapInboundClaims is off — see — so the claim is spelled as the
+ /// provider issued it rather than as a WS-Federation URI. Null is treated as "no bound from the
+ /// token", which the bearer handler's RequireExpirationTime should make unreachable; the
+ /// lifetime cap covers it either way.
+ ///
+ private DateTimeOffset? TokenExpiry() =>
+ long.TryParse(
+ HttpContext.User.FindFirstValue("exp"),
+ NumberStyles.Integer,
+ CultureInfo.InvariantCulture,
+ out var seconds)
+ ? DateTimeOffset.FromUnixTimeSeconds(seconds)
+ : null;
+
+ private static async Task CloseAsync(WebSocket socket, Closure closure)
+ {
+ if (socket.State is not (WebSocketState.Open or WebSocketState.CloseReceived))
+ {
+ return;
+ }
+
+ using var timeout = new CancellationTokenSource(CloseTimeout);
+
+ try
+ {
+ await socket
+ .CloseOutputAsync((WebSocketCloseStatus)closure.Code, closure.Reason, timeout.Token)
+ .ConfigureAwait(false);
+ }
+ catch (Exception exception)
+ when (exception is OperationCanceledException or WebSocketException or ObjectDisposedException)
+ {
+ // The peer is already gone. There is nothing to tell it and nothing to recover.
+ }
+ }
+
+ ///
+ /// Awaits a pump loop, treating its cancellation and its socket faults as the ordinary end.
+ ///
+ ///
+ /// Every one of these loops ends by being cancelled or by the socket going away, so an exception
+ /// here is the expected shape of "this connection is over" rather than a fault to propagate — and
+ /// propagating it would skip the close frame the other side is waiting for.
+ ///
+ private static async Task Settled(Task loop)
+ {
+ try
+ {
+ await loop.ConfigureAwait(false);
+ }
+ catch (Exception exception)
+ when (exception is OperationCanceledException or WebSocketException or ObjectDisposedException)
+ {
+ // Expected.
+ }
+ }
+
+ /// Why the socket is being closed, decided by whichever loop ended first.
+ ///
+ /// Mutable and shared, and safe without a lock for one specific reason: it is written by the pump
+ /// loops and read only after over all of them, which is a
+ /// memory barrier. Writes race only with each other, and any of them is a true answer.
+ ///
+ private sealed class Closure(int code, string reason)
+ {
+ internal int Code { get; private set; } = code;
+
+ internal string Reason { get; private set; } = reason;
+
+ internal void Set(int code, string reason)
+ {
+ Code = code;
+ Reason = reason;
+ }
+ }
+}
diff --git a/src/DodoSSH.Api/Features/Events/EventsLog.cs b/src/DodoSSH.Api/Features/Events/EventsLog.cs
new file mode 100644
index 0000000..b912b04
--- /dev/null
+++ b/src/DodoSSH.Api/Features/Events/EventsLog.cs
@@ -0,0 +1,68 @@
+namespace DodoSSH.Api.Features.Events;
+
+/// Source-generated log messages for the event socket.
+///
+/// Ids and counts only, as everywhere else. A notice carries no ciphertext to leak, but which vault
+/// changed and when is still the metadata ADR 0001 asks be kept to what is diagnostically useful.
+///
+internal static partial class EventsLog
+{
+ [LoggerMessage(
+ EventId = 2201,
+ Level = LogLevel.Debug,
+ Message = "Event socket opened for user {UserId} following {VaultCount} vault(s); "
+ + "{ConnectionCount} open on this node.")]
+ internal static partial void ConnectionOpened(
+ ILogger logger,
+ Guid userId,
+ int vaultCount,
+ int connectionCount);
+
+ [LoggerMessage(
+ EventId = 2202,
+ Level = LogLevel.Debug,
+ Message = "Event socket closed for user {UserId}; {ConnectionCount} open on this node.")]
+ internal static partial void ConnectionClosed(ILogger logger, Guid userId, int connectionCount);
+
+ ///
+ /// Information rather than Debug: a refused socket is a client that will poll for the rest of its
+ /// session, and an operator seeing these has a cap to raise.
+ ///
+ [LoggerMessage(
+ EventId = 2203,
+ Level = LogLevel.Information,
+ Message = "Refused an event socket for user {UserId}: {Limit} is already reached.")]
+ internal static partial void ConnectionRefused(ILogger logger, Guid userId, string limit);
+
+ [LoggerMessage(
+ EventId = 2204,
+ Level = LogLevel.Debug,
+ Message = "Announced vault {VaultId} at sequence {Sequence} to {ConnectionCount} socket(s).")]
+ internal static partial void VaultChangePublished(
+ ILogger logger,
+ Guid vaultId,
+ long sequence,
+ int connectionCount);
+
+ [LoggerMessage(
+ EventId = 2205,
+ Level = LogLevel.Debug,
+ Message = "Announced a vault access change to {ConnectionCount} socket(s) of user {UserId}.")]
+ internal static partial void AccessChangePublished(ILogger logger, Guid userId, int connectionCount);
+
+ ///
+ /// Warning, and it is worth being loud: the socket is still open and still delivering, but it is
+ /// delivering about a vault set that may be stale. Everything else here is routine.
+ ///
+ [LoggerMessage(
+ EventId = 2206,
+ Level = LogLevel.Warning,
+ Message = "Could not re-resolve which vaults user {UserId}'s event socket may follow.")]
+ internal static partial void AccessRefreshFailed(ILogger logger, Guid userId, Exception exception);
+
+ [LoggerMessage(
+ EventId = 2207,
+ Level = LogLevel.Debug,
+ Message = "Closing user {UserId}'s event socket: {Reason}.")]
+ internal static partial void ClosingConnection(ILogger logger, Guid userId, string reason);
+}
diff --git a/src/DodoSSH.Api/Features/Events/VaultEventHub.cs b/src/DodoSSH.Api/Features/Events/VaultEventHub.cs
new file mode 100644
index 0000000..dbd918e
--- /dev/null
+++ b/src/DodoSSH.Api/Features/Events/VaultEventHub.cs
@@ -0,0 +1,242 @@
+using System.Collections.Concurrent;
+using System.Collections.Frozen;
+using System.Threading.Channels;
+using DodoSSH.Api.Setup;
+using DodoSSH.Contracts;
+using Microsoft.Extensions.Options;
+
+namespace DodoSSH.Api.Features.Events;
+
+///
+/// Tells connected clients that something they can read has moved.
+///
+///
+///
+/// Every method is void and returns having queued, never having sent. That is the contract, not
+/// an implementation detail: the callers are write paths that have just committed a transaction, and a
+/// publish that could block on a slow socket would make one client's bad network everybody else's
+/// latency. A notice that cannot be queued is dropped, which is safe because the client polls anyway.
+/// See ADR 0012.
+///
+///
+/// An interface because this is the seam a multi-node backplane implements — PostgreSQL
+/// LISTEN/NOTIFY is the obvious one and needs no infrastructure this stack does not
+/// already run. It is deliberately not implemented: fan-out today is in-process, so a deployment with
+/// more than one API replica notices writes handled by other replicas on the polling interval rather
+/// than at once. That is the behaviour before this feature existed, which is why it degrades rather
+/// than breaks.
+///
+///
+public interface IVaultEventPublisher
+{
+ /// Announces that a vault's change log has reached .
+ ///
+ /// Call after the transaction commits, and outside the per-vault advisory lock ADR 0003
+ /// takes. A notice sent from inside names a sequence no reader can see yet, and holds the vault's
+ /// write lock across a socket write.
+ ///
+ void VaultChanged(Guid vaultId, long sequence);
+
+ /// Announces that the set of vaults an account can reach is no longer what it was.
+ ///
+ /// Takes the recipient, not the actor. Sharing is something one account does to another's
+ /// list, and it is the other account that has to re-read.
+ ///
+ void VaultAccessChanged(Guid userId);
+}
+
+///
+/// Every event socket this node is holding.
+///
+///
+///
+/// Publishing walks the whole connection list and asks each one whether it cares, rather than keeping
+/// an index from vault to subscribers. With a per-node connection cap in the hundreds and an event rate
+/// bounded by how often people edit keychains, the walk is not measurable — and the index is not free:
+/// a connection's vault set is re-resolved while it is live, so every re-subscription would have to
+/// move it between buckets under a lock that publishing also takes. The simpler shape is the one whose
+/// races are obvious.
+///
+///
+/// A singleton, holding no scoped service and no database context. Connections outlive requests by
+/// design and anything request-scoped they captured would outlive its scope with them.
+///
+///
+internal sealed class VaultEventHub(
+ IOptions options,
+ TimeProvider clock,
+ ILogger logger) : IVaultEventPublisher
+{
+ private readonly ConcurrentDictionary connections = new();
+
+ ///
+ /// Serialises admission so the caps are caps rather than approximations.
+ ///
+ ///
+ /// Counting and inserting under one lock, because the two done separately let N simultaneous
+ /// connects all read the same under-cap count and all insert. Contended only by connects, which
+ /// happen once per client per session; publishing never takes it.
+ ///
+ private readonly Lock admission = new();
+
+ /// How many sockets this node is holding. Diagnostics and tests.
+ internal int Count => connections.Count;
+
+ ///
+ /// Admits a socket, or refuses it because a cap is already met.
+ ///
+ /// The connection, or null when a limit refused it.
+ internal VaultEventConnection? TryAdmit(Guid userId, FrozenSet vaults)
+ {
+ var limits = options.Value;
+
+ lock (admission)
+ {
+ if (connections.Count >= limits.MaxConnectionsTotal)
+ {
+ EventsLog.ConnectionRefused(logger, userId, "the node limit");
+ return null;
+ }
+
+ var held = 0;
+ foreach (var existing in connections.Values)
+ {
+ if (existing.UserId == userId && ++held >= limits.MaxConnectionsPerUser)
+ {
+ EventsLog.ConnectionRefused(logger, userId, "the per-account limit");
+ return null;
+ }
+ }
+
+ var connection = new VaultEventConnection(userId, vaults, limits.OutboundQueueDepth);
+
+ // Cannot collide: the id is fresh and this is the only insert.
+ connections[connection.Id] = connection;
+
+ EventsLog.ConnectionOpened(logger, userId, vaults.Count, connections.Count);
+
+ return connection;
+ }
+ }
+
+ /// Forgets a socket that has closed.
+ internal void Remove(VaultEventConnection connection)
+ {
+ ArgumentNullException.ThrowIfNull(connection);
+
+ connections.TryRemove(connection.Id, out _);
+ connection.Complete();
+
+ EventsLog.ConnectionClosed(logger, connection.UserId, connections.Count);
+ }
+
+ ///
+ public void VaultChanged(Guid vaultId, long sequence)
+ {
+ var notice = new VaultEvent(
+ VaultEventKinds.VaultChanged,
+ VaultId: vaultId,
+ Sequence: sequence,
+ ServerTime: clock.GetUtcNow());
+
+ var delivered = 0;
+
+ foreach (var connection in connections.Values)
+ {
+ if (connection.IsSubscribedTo(vaultId) && connection.TryEnqueue(notice))
+ {
+ delivered++;
+ }
+ }
+
+ if (delivered > 0)
+ {
+ EventsLog.VaultChangePublished(logger, vaultId, sequence, delivered);
+ }
+ }
+
+ ///
+ public void VaultAccessChanged(Guid userId)
+ {
+ var notice = new VaultEvent(VaultEventKinds.VaultsChanged, ServerTime: clock.GetUtcNow());
+
+ var delivered = 0;
+
+ foreach (var connection in connections.Values)
+ {
+ if (connection.UserId == userId && connection.TryEnqueue(notice))
+ {
+ delivered++;
+ }
+ }
+
+ if (delivered > 0)
+ {
+ EventsLog.AccessChangePublished(logger, userId, delivered);
+ }
+ }
+}
+
+///
+/// One open socket, as the hub sees it.
+///
+///
+/// Deliberately knows nothing about WebSockets. The hub queues frames here and the endpoint's pump
+/// takes them away, which is what keeps a publish from ever touching a socket — and what lets the
+/// whole fan-out be tested without one.
+///
+internal sealed class VaultEventConnection
+{
+ private readonly Channel outbound;
+
+ private FrozenSet vaults;
+
+ internal VaultEventConnection(Guid userId, FrozenSet vaults, int queueDepth)
+ {
+ Id = Guid.CreateVersion7();
+ UserId = userId;
+ this.vaults = vaults;
+
+ // DropOldest, and the choice is what makes a slow reader harmless. A notice says "vault X has
+ // moved to at least sequence N", so a newer one subsumes the one it displaces and the client's
+ // answer — pull that vault — is identical either way. The writer therefore never waits and
+ // TryWrite never fails, which is what lets the publish path be non-blocking and void.
+ outbound = Channel.CreateBounded(new BoundedChannelOptions(queueDepth)
+ {
+ FullMode = BoundedChannelFullMode.DropOldest,
+ SingleReader = true,
+ SingleWriter = false,
+ });
+ }
+
+ /// Identifies this connection within the hub. Never sent to a client.
+ internal Guid Id { get; }
+
+ /// The account that opened it.
+ internal Guid UserId { get; }
+
+ /// Frames waiting to be written to the socket.
+ internal ChannelReader Outbound => outbound.Reader;
+
+ /// How many vaults this socket currently follows.
+ internal int VaultCount => Volatile.Read(ref vaults).Count;
+
+ /// Whether a change to this vault concerns this socket.
+ internal bool IsSubscribedTo(Guid vaultId) => Volatile.Read(ref vaults).Contains(vaultId);
+
+ ///
+ /// Replaces what this socket follows, after its account's access was re-resolved.
+ ///
+ ///
+ /// A whole-set swap of an immutable set rather than a mutation, so a publish walking the list
+ /// concurrently reads either the old set or the new one and never a half-built one. No lock: the
+ /// only writer is this connection's own pump.
+ ///
+ internal void Resubscribe(FrozenSet replacement) => Volatile.Write(ref vaults, replacement);
+
+ /// Queues a frame. Never blocks, and never fails — see the channel's full mode.
+ internal bool TryEnqueue(VaultEvent frame) => outbound.Writer.TryWrite(frame);
+
+ /// Signals that nothing more will be queued, which ends the pump's drain loop.
+ internal void Complete() => outbound.Writer.TryComplete();
+}
diff --git a/src/DodoSSH.Api/Features/Meta/MetaEndpoints.cs b/src/DodoSSH.Api/Features/Meta/MetaEndpoints.cs
index 3533372..e9a3b7a 100644
--- a/src/DodoSSH.Api/Features/Meta/MetaEndpoints.cs
+++ b/src/DodoSSH.Api/Features/Meta/MetaEndpoints.cs
@@ -19,6 +19,7 @@ namespace DodoSSH.Api.Features.Meta;
internal sealed class GetMetaEndpoint(
IOptions sync,
IOptions relay,
+ IOptions events,
IOptions server)
: EndpointWithoutRequest>
{
@@ -52,6 +53,14 @@ internal sealed class GetMetaEndpoint(
features.Add(RelayFeature);
}
+ // Advertised so a client knows whether to hold a socket open or rely on its timer. Absence is
+ // not an error — synchronising on a timer is the supported behaviour and the socket only makes
+ // it early — which is why this is a feature flag rather than a version bump. See ADR 0012.
+ if (events.Value.Enabled)
+ {
+ features.Add(VaultEvents.Feature);
+ }
+
return Task.FromResult(TypedResults.Ok(new MetaResponse(
ServerVersion: ServerVersion,
ApiVersions: [1],
diff --git a/src/DodoSSH.Api/Features/Sync/SyncEndpoints.cs b/src/DodoSSH.Api/Features/Sync/SyncEndpoints.cs
index bf402da..0f8d1d8 100644
--- a/src/DodoSSH.Api/Features/Sync/SyncEndpoints.cs
+++ b/src/DodoSSH.Api/Features/Sync/SyncEndpoints.cs
@@ -1,4 +1,5 @@
using DodoSSH.Api.Authorization;
+using DodoSSH.Api.Features.Events;
using DodoSSH.Api.Setup;
using DodoSSH.Contracts;
using DodoSSH.Domain.Authorization;
@@ -81,6 +82,7 @@ internal sealed class SyncPullEndpoint(
internal sealed class SyncPushEndpoint(
ICurrentUserContext currentUser,
IVaultAccessService vaultAccess,
+ IVaultEventPublisher events,
SyncService sync)
: Endpoint, NotFound, ProblemHttpResult>>
{
@@ -127,6 +129,8 @@ internal sealed class SyncPushEndpoint(
// single stale item cannot block everything else a client queued while offline.
var response = await sync.PushAsync(access.Vault!, user.Id, req, ct).ConfigureAwait(false);
+ Announce(access.Vault!.Id, response);
+
return TypedResults.Ok(response);
}
catch (PushBatchTooLargeException exception)
@@ -142,4 +146,41 @@ internal sealed class SyncPushEndpoint(
StatusCodes.Status400BadRequest, ProblemCodes.PushBatchTooLarge, exception.Message);
}
}
+
+ ///
+ /// Tells every socket following this vault that it has moved.
+ ///
+ ///
+ ///
+ /// Here rather than inside , and that placement is the point:
+ /// the push has committed and released the per-vault advisory lock by the time this runs. Announced
+ /// from inside, it would name a sequence no reader could see yet and would hold the lock that
+ /// serialises writers across a fan-out. See ADR 0003 and ADR 0012.
+ ///
+ ///
+ /// The highest applied sequence, ignoring duplicates: a duplicate means an earlier push of
+ /// that operation already landed, and it was announced then. Nothing applied means nothing to say —
+ /// a batch of pure conflicts moved no vault, and announcing one anyway would have every client pull
+ /// for a change that is not there.
+ ///
+ ///
+ private void Announce(Guid vaultId, SyncPushResponse response)
+ {
+ var highest = 0L;
+
+ foreach (var result in response.Results)
+ {
+ if (result.Status == SyncOperationStatus.Applied
+ && result.ChangeSequence is { } sequence
+ && sequence > highest)
+ {
+ highest = sequence;
+ }
+ }
+
+ if (highest > 0)
+ {
+ events.VaultChanged(vaultId, highest);
+ }
+ }
}
diff --git a/src/DodoSSH.Api/Features/Teams/TeamService.cs b/src/DodoSSH.Api/Features/Teams/TeamService.cs
index 737d786..ff681f3 100644
--- a/src/DodoSSH.Api/Features/Teams/TeamService.cs
+++ b/src/DodoSSH.Api/Features/Teams/TeamService.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using DodoSSH.Api.Features.Events;
using DodoSSH.Contracts;
using DodoSSH.Domain;
using DodoSSH.Infrastructure;
@@ -62,6 +63,7 @@ internal readonly record struct TeamAccess(Team? Team, TeamRole Role)
internal sealed class TeamService(
DodoDbContext database,
TimeProvider clock,
+ IVaultEventPublisher events,
ILogger logger)
{
/// Longest acceptable slug. Matches the column.
@@ -548,6 +550,11 @@ internal sealed class TeamService(
TeamLog.MemberAdded(logger, teamId, target.Id, role, actor.Id);
+ // Membership is what the server will serve, so every vault this team owns has just appeared in
+ // the new member's list — before anybody wraps a key to them, which is a separate act and its
+ // own notice. Told at once rather than on their next pass. See ADR 0012.
+ events.VaultAccessChanged(target.Id);
+
return await DescribeAsync(target, membership, cancellationToken).ConfigureAwait(false);
}
@@ -744,6 +751,11 @@ internal sealed class TeamService(
}).ConfigureAwait(false);
TeamLog.MemberRemoved(logger, teamId, memberId, actor.Id, revoked);
+
+ // After the commit, so their client re-reads a list the server has already stopped serving
+ // those vaults from. Their open socket re-resolves as it forwards this, which is what stops it
+ // announcing changes to vaults they have just lost.
+ events.VaultAccessChanged(memberId);
}
/// Revokes one user's grants on every vault a team owns, and flags each for rekey.
diff --git a/src/DodoSSH.Api/Features/Teams/VaultGrantService.cs b/src/DodoSSH.Api/Features/Teams/VaultGrantService.cs
index 277d8b1..3506c01 100644
--- a/src/DodoSSH.Api/Features/Teams/VaultGrantService.cs
+++ b/src/DodoSSH.Api/Features/Teams/VaultGrantService.cs
@@ -1,4 +1,5 @@
using System.Security.Cryptography;
+using DodoSSH.Api.Features.Events;
using DodoSSH.Contracts;
using DodoSSH.Domain;
using DodoSSH.Infrastructure;
@@ -27,6 +28,7 @@ namespace DodoSSH.Api.Features.Teams;
internal sealed class VaultGrantService(
DodoDbContext database,
TimeProvider clock,
+ IVaultEventPublisher events,
ILogger logger)
{
///
@@ -414,6 +416,11 @@ internal sealed class VaultGrantService(
TeamLog.GrantIssued(
logger, vault.Id, generation, request.RecipientUserId, actor.Id);
+
+ // The recipient, never the actor. This is the whole of what makes a shared vault arrive at
+ // once rather than on the recipient's next pass — and it is the case the README has had to
+ // apologise for since sharing shipped. See ADR 0012.
+ events.VaultAccessChanged(request.RecipientUserId);
}
///
@@ -701,6 +708,11 @@ internal sealed class VaultGrantService(
TeamLog.GrantRevoked(logger, vault.Id, recipientUserId, actor.Id);
+ // Told so their client stops showing a vault it can no longer open, rather than leaving it
+ // listed until the next pass. It does not reach what they already pulled — nothing can, see
+ // ADR 0001 — and the server-side effect is immediate regardless of whether this arrives.
+ events.VaultAccessChanged(recipientUserId);
+
return true;
}
diff --git a/src/DodoSSH.Api/Program.cs b/src/DodoSSH.Api/Program.cs
index abc8cdb..d5702d6 100644
--- a/src/DodoSSH.Api/Program.cs
+++ b/src/DodoSSH.Api/Program.cs
@@ -1,4 +1,5 @@
using DodoSSH.Api.Authorization;
+using DodoSSH.Api.Features.Events;
using DodoSSH.Api.Features.Identity;
using DodoSSH.Api.Features.Sync;
using DodoSSH.Api.Features.Teams;
@@ -47,6 +48,14 @@ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddSingleton();
+// A singleton, because the sockets it holds outlive the requests that opened them. Registered twice
+// resolving to the same instance, for the reason the invitation claim above is: the endpoint needs the
+// whole hub — admit, remove, count — while the write paths that announce a change need only the two
+// methods that announce one, and should not gain a reference to connection management to get them.
+builder.Services.AddSingleton();
+builder.Services.AddSingleton(
+ provider => provider.GetRequiredService());
+
// Scoped rather than the AddAuthorization default of singleton: the handler reads the request's
// DbContext, and a singleton would capture one for the lifetime of the process.
builder.Services.AddScoped();
@@ -65,6 +74,13 @@ var app = builder.Build();
app.BlockFastEndpointsRouteTable();
+// Before the authentication middleware, because the upgrade handshake has to survive it: the events
+// endpoint answers an ordinary authenticated request that happens to become a socket, and without
+// this the upgrade is never offered and the handler sees a plain GET. No allow-list of origins is
+// configured, deliberately — every client here is a native application sending a bearer token, so
+// there is no browser origin to trust and nothing a cross-site request could reach without one.
+app.UseWebSockets();
+
app.UseAuthentication();
app.UseAuthorization();
diff --git a/src/DodoSSH.Api/Setup/Configuration.cs b/src/DodoSSH.Api/Setup/Configuration.cs
index 6ed888f..1deb6ef 100644
--- a/src/DodoSSH.Api/Setup/Configuration.cs
+++ b/src/DodoSSH.Api/Setup/Configuration.cs
@@ -38,6 +38,22 @@ internal static class Configuration
"Sync:DefaultPullLimit must not exceed Sync:MaxPullLimit.")
.ValidateOnStart();
+ services.AddOptions()
+ .BindConfiguration(EventsOptions.SectionName)
+ .ValidateDataAnnotations()
+ .Validate(
+ options => options.HeartbeatInterval > TimeSpan.Zero,
+ "Events:HeartbeatInterval must be greater than zero.")
+ .Validate(
+ options => options.AccessRefreshInterval > TimeSpan.Zero,
+ "Events:AccessRefreshInterval must be greater than zero.")
+ .Validate(
+ options => options.MaxConnectionDuration > options.AccessRefreshInterval,
+ "Events:MaxConnectionDuration must exceed Events:AccessRefreshInterval; a connection "
+ + "that never lives long enough to re-read its own access has none of the bound that "
+ + "setting exists to provide.")
+ .ValidateOnStart();
+
services.AddOptions()
.BindConfiguration(RelayOptions.SectionName)
.ValidateDataAnnotations()
diff --git a/src/DodoSSH.Api/Setup/DodoOptions.cs b/src/DodoSSH.Api/Setup/DodoOptions.cs
index d51d5c1..31ed25d 100644
--- a/src/DodoSSH.Api/Setup/DodoOptions.cs
+++ b/src/DodoSSH.Api/Setup/DodoOptions.cs
@@ -159,6 +159,82 @@ public sealed class RelayOptions
public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30);
}
+/// Realtime push settings. See ADR 0012.
+///
+/// Every one of these bounds a socket rather than a feature: with the whole thing off, or every cap
+/// met, clients synchronise on their timer exactly as they did before this existed. That is what
+/// makes it safe for an operator to turn any of them down.
+///
+public sealed class EventsOptions
+{
+ /// Configuration section name.
+ public const string SectionName = "Events";
+
+ ///
+ /// Whether this deployment pushes vault changes at all.
+ ///
+ ///
+ /// On by default, unlike the relay: this needs no outbound network, no target resolution and no
+ /// new trust, and a deployment behind a proxy that will not upgrade should say so here rather than
+ /// have every client discover it by failing.
+ ///
+ public bool Enabled { get; set; } = true;
+
+ /// Maximum concurrent sockets per node.
+ [Range(1, 100_000)]
+ public int MaxConnectionsTotal { get; set; } = 500;
+
+ ///
+ /// Maximum concurrent sockets per account.
+ ///
+ ///
+ /// Per account rather than per device, because the server cannot see a device here. Eight is a
+ /// laptop, a desktop, a phone and room to reconnect before the old socket has been reaped.
+ ///
+ [Range(1, 1000)]
+ public int MaxConnectionsPerUser { get; set; } = 8;
+
+ ///
+ /// How many notices may be queued for one socket before the oldest are dropped.
+ ///
+ ///
+ /// A notice names a vault and a position, so a newer one subsumes the one it replaces. The depth
+ /// therefore buys smoothness over a brief stall and nothing else — losing the tail of a burst
+ /// costs a client nothing, because the newest notice still says to pull.
+ ///
+ [Range(1, 10_000)]
+ public int OutboundQueueDepth { get; set; } = 64;
+
+ ///
+ /// How often the server pings an idle socket.
+ ///
+ ///
+ /// Below the sixty seconds most reverse proxies idle out at, because a silent socket that a proxy
+ /// has quietly dropped is indistinguishable from a quiet one until something is sent down it.
+ ///
+ public TimeSpan HeartbeatInterval { get; set; } = TimeSpan.FromSeconds(30);
+
+ ///
+ /// How often an open socket re-reads which vaults its account may follow.
+ ///
+ ///
+ /// The backstop for a grant withdrawn mid-connection. Grants and membership changes publish
+ /// immediately, so this is what covers the paths that do not — and what bounds the window if one
+ /// is ever added without remembering to.
+ ///
+ public TimeSpan AccessRefreshInterval { get; set; } = TimeSpan.FromMinutes(5);
+
+ ///
+ /// The longest any one socket may live, regardless of its token.
+ ///
+ ///
+ /// A socket normally ends at its access token's expiry, which is far shorter. This is the bound
+ /// for a provider that issues long-lived tokens, and it is what makes "no connection is older than
+ /// this" a property of the server rather than of the identity provider's configuration.
+ ///
+ public TimeSpan MaxConnectionDuration { get; set; } = TimeSpan.FromHours(12);
+}
+
/// Sync protocol limits.
public sealed class SyncOptions
{
diff --git a/src/DodoSSH.Api/Setup/EndpointRegistration.cs b/src/DodoSSH.Api/Setup/EndpointRegistration.cs
index bb9d545..5260569 100644
--- a/src/DodoSSH.Api/Setup/EndpointRegistration.cs
+++ b/src/DodoSSH.Api/Setup/EndpointRegistration.cs
@@ -1,3 +1,4 @@
+using DodoSSH.Api.Features.Events;
using DodoSSH.Api.Features.Identity;
using DodoSSH.Api.Features.Meta;
using DodoSSH.Api.Features.Sync;
@@ -43,6 +44,7 @@ internal static class EndpointRegistration
typeof(ReadKeyLogEndpoint),
typeof(SyncPullEndpoint),
typeof(SyncPushEndpoint),
+ typeof(VaultEventsEndpoint),
typeof(CreateTeamEndpoint),
typeof(ListTeamsEndpoint),
typeof(UpdateTeamEndpoint),
diff --git a/src/DodoSSH.Api/appsettings.json b/src/DodoSSH.Api/appsettings.json
index 6df91bf..fde102b 100644
--- a/src/DodoSSH.Api/appsettings.json
+++ b/src/DodoSSH.Api/appsettings.json
@@ -26,6 +26,11 @@
"MaxConcurrentSessionsPerUser": 10,
"MaxConcurrentSessionsTotal": 200
},
+ "Events": {
+ "Enabled": true,
+ "MaxConnectionsTotal": 500,
+ "MaxConnectionsPerUser": 8
+ },
"Sync": {
"MaxOperationsPerPush": 500,
"MaxPayloadBytes": 8388608,
diff --git a/src/DodoSSH.Client.Android/Views/HostsScreen.axaml b/src/DodoSSH.Client.Android/Views/HostsScreen.axaml
index 821f6f2..684f2fd 100644
--- a/src/DodoSSH.Client.Android/Views/HostsScreen.axaml
+++ b/src/DodoSSH.Client.Android/Views/HostsScreen.axaml
@@ -125,7 +125,21 @@
-
+
+
+
+
+
+
+
+
+
@@ -262,10 +276,12 @@
@@ -279,7 +295,7 @@
+ Text="A host in a shared vault is readable by everybody holding that vault's key. It can be moved out later, with MOVE under the host — what it cannot do is become unreadable to somebody who has already synced it." />
@@ -367,6 +383,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/DodoSSH.Client.Api/VaultEventStream.cs b/src/DodoSSH.Client.Api/VaultEventStream.cs
new file mode 100644
index 0000000..df1cb0b
--- /dev/null
+++ b/src/DodoSSH.Client.Api/VaultEventStream.cs
@@ -0,0 +1,552 @@
+using System.Net.WebSockets;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Threading.Channels;
+using DodoSSH.Contracts;
+
+namespace DodoSSH.Client.Api;
+
+///
+/// A server's "pull now" notices, as everything above the transport needs them.
+///
+///
+///
+/// A queue to read from rather than an event to subscribe to, and that shape is the point: the one
+/// consumer is a synchronisation loop that already waits on a timer, so it can wait on this the same
+/// way and keep every continuation on the thread it started from. An event would deliver on whichever
+/// thread the socket happened to complete on, which in a user interface is the difference between
+/// working and an intermittent rendering fault nobody can reproduce.
+///
+///
+/// Reading this is never how a change is applied. A notice says which vault moved and nothing
+/// else; the answer to it is the ordinary delta pull. See ADR 0012.
+///
+///
+public interface IVaultEventStream : IDisposable
+{
+ /// Whether a socket is currently established.
+ ///
+ /// For the interface to say whether it is live, not for a caller to branch on before reading:
+ /// synchronising is correct whether or not this is true, because the timer is the fallback.
+ ///
+ bool IsConnected { get; }
+
+ ///
+ /// Waits for the next notice.
+ ///
+ ///
+ /// Connects on the first call and reconnects for as long as it is read, so a caller neither starts
+ /// nor restarts anything. A server that cannot be reached is not an error here — it is a wait that
+ /// has not finished — because the caller's alternative is the timer it is already running.
+ ///
+ ValueTask ReadAsync(CancellationToken cancellationToken);
+
+ ///
+ /// Takes a notice if one is already waiting, without blocking.
+ ///
+ /// Whether there was one.
+ ///
+ /// How a caller coalesces a burst. Five people saving at once produces five notices whose answer
+ /// is a single synchronisation pass, so the loop reads one, waits a moment, and swallows the rest
+ /// rather than running the same pull five times.
+ ///
+ bool TryRead(out VaultEvent notice);
+}
+
+///
+/// A stream that never delivers anything.
+///
+///
+/// For a server that does not advertise the events feature, and for tests. Deliberately waits
+/// for ever rather than completing: a caller selecting between this and a timer must fall through to
+/// the timer, and a read that returned immediately would spin that loop as fast as the machine allows.
+///
+public sealed class IdleVaultEventStream : IVaultEventStream
+{
+ /// The one instance. It holds nothing.
+ public static IdleVaultEventStream Instance { get; } = new();
+
+ ///
+ public bool IsConnected => false;
+
+ ///
+ public async ValueTask ReadAsync(CancellationToken cancellationToken)
+ {
+ await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false);
+
+ // Unreachable: the delay above only ever ends by throwing.
+ return new VaultEvent(VaultEventKinds.Ping);
+ }
+
+ ///
+ public bool TryRead(out VaultEvent notice)
+ {
+ notice = new VaultEvent(VaultEventKinds.Ping);
+ return false;
+ }
+
+ ///
+ public void Dispose()
+ {
+ // Nothing is held.
+ }
+}
+
+/// Tuning for .
+///
+/// Every value here bounds a reconnection rather than a feature. With the socket permanently
+/// unavailable the client synchronises on its timer, so the cost of getting these wrong is latency,
+/// never correctness.
+///
+public sealed record VaultEventStreamOptions
+{
+ /// The defaults.
+ public static VaultEventStreamOptions Default { get; } = new();
+
+ /// How long to wait before the first reconnection attempt.
+ public TimeSpan InitialBackoff { get; init; } = TimeSpan.FromSeconds(1);
+
+ /// The longest the backoff may grow to.
+ ///
+ /// A minute, which is the polling interval: past that point reconnecting sooner buys nothing,
+ /// because the timer has already done the work the socket would have prompted.
+ ///
+ public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(1);
+
+ ///
+ /// How long a socket may be silent before it is presumed dead.
+ ///
+ ///
+ /// The server pings on an interval it states in its hello, so silence past a multiple of
+ /// that means the connection is gone rather than idle — which is otherwise indistinguishable, and
+ /// is exactly what a reverse proxy that quietly drops idle sockets produces. Used only until a
+ /// hello arrives; after that the server's own figure is trusted.
+ ///
+ public TimeSpan InitialSilenceTimeout { get; init; } = TimeSpan.FromSeconds(90);
+
+ /// How many notices may be waiting before the oldest are dropped.
+ ///
+ /// Small on purpose. A notice means "pull that vault", so a newer one subsumes the one it
+ /// displaces; a backlog would only make the loop pull repeatedly for work it has already done.
+ ///
+ public int QueueDepth { get; init; } = 32;
+}
+
+///
+/// Holds a socket to one server open, and hands over what it says.
+///
+///
+///
+/// The whole class is a reconnection policy. A dropped socket is the ordinary case — laptops sleep,
+/// proxies time out, tokens expire, servers are redeployed — so nothing here treats a failure as
+/// exceptional: it backs off and dials again, for as long as somebody is reading.
+///
+///
+/// It is safe to have no server at all. Every failure path ends in "wait, then try again", and the
+/// caller's synchronisation timer runs regardless, which is what makes it correct for this class to
+/// stay silent about problems rather than surface them.
+///
+///
+public sealed class VaultEventStream : IVaultEventStream, IAsyncDisposable
+{
+ private readonly Uri endpoint;
+ private readonly IAccessTokenProvider tokens;
+ private readonly TimeProvider clock;
+ private readonly VaultEventStreamOptions options;
+ private readonly Func> connect;
+ private readonly Channel notices;
+ private readonly CancellationTokenSource closing = new();
+ private readonly Lock starting = new();
+
+ private Task? pump;
+ private bool disposed;
+
+ /// Creates a stream against one server.
+ /// The server's base URL, as an ordinary http or https address.
+ /// Supplies a bearer token, refreshing it when it is due.
+ /// Time source, for the backoff and the silence timeout.
+ /// Tuning, or null for the defaults.
+ public VaultEventStream(
+ Uri serverUrl,
+ IAccessTokenProvider tokens,
+ TimeProvider clock,
+ VaultEventStreamOptions? options = null)
+ : this(serverUrl, tokens, clock, DialAsync, options)
+ {
+ }
+
+ ///
+ /// The connector is injected so the suite can drive this against a test host's in-memory socket.
+ /// Reconnection is the entire behaviour of this class, and testing it against a real network would
+ /// mean testing it against the one thing that cannot be made to fail on demand.
+ ///
+ internal VaultEventStream(
+ Uri serverUrl,
+ IAccessTokenProvider tokens,
+ TimeProvider clock,
+ Func> connect,
+ VaultEventStreamOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(serverUrl);
+ ArgumentNullException.ThrowIfNull(tokens);
+ ArgumentNullException.ThrowIfNull(clock);
+ ArgumentNullException.ThrowIfNull(connect);
+
+ endpoint = EventsUrl(serverUrl);
+ this.tokens = tokens;
+ this.clock = clock;
+ this.connect = connect;
+ this.options = options ?? VaultEventStreamOptions.Default;
+
+ notices = Channel.CreateBounded(new BoundedChannelOptions(this.options.QueueDepth)
+ {
+ FullMode = BoundedChannelFullMode.DropOldest,
+ SingleReader = true,
+ SingleWriter = true,
+ });
+ }
+
+ ///
+ public bool IsConnected { get; private set; }
+
+ ///
+ public ValueTask ReadAsync(CancellationToken cancellationToken)
+ {
+ ObjectDisposedException.ThrowIf(disposed, this);
+
+ Start();
+
+ return notices.Reader.ReadAsync(cancellationToken);
+ }
+
+ ///
+ ///
+ /// Does not start the connection, unlike : a caller draining a burst has
+ /// already read one notice, and "is there another right now" is not a reason to dial a server.
+ ///
+ public bool TryRead(out VaultEvent notice) => notices.Reader.TryRead(out notice!);
+
+ ///
+ /// Ends the connection, without waiting for it to unwind.
+ ///
+ ///
+ /// What a shell calls when a connection is dropped, from a synchronous path that must not block —
+ /// IVaultServer is , and blocking on a socket teardown from the
+ /// user-interface thread is exactly the sync-over-async this repository bans. Cancelling is enough:
+ /// every loop reads the token, and the pump has nothing to flush.
+ ///
+ public void Dispose()
+ {
+ if (disposed)
+ {
+ return;
+ }
+
+ disposed = true;
+ closing.Cancel();
+
+ // The source is deliberately left undisposed. The pump may still be inside a linked token
+ // source derived from this one, and disposing a parent out from under a live child is how a
+ // clean shutdown becomes an ObjectDisposedException on a background thread. It holds no timer
+ // and no handle once cancelled; DisposeAsync is the path that cleans it up properly.
+ }
+
+ /// Ends the connection and waits for it to unwind.
+ /// The deterministic form, for a caller that can await one — tests, mostly.
+ public async ValueTask DisposeAsync()
+ {
+ if (disposed)
+ {
+ return;
+ }
+
+ disposed = true;
+
+ await closing.CancelAsync().ConfigureAwait(false);
+
+ if (pump is not null)
+ {
+ try
+ {
+ await pump.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ // The point of the cancel above.
+ }
+ }
+
+ closing.Dispose();
+ }
+
+ ///
+ /// Turns a server's base URL into its event socket's.
+ ///
+ ///
+ /// The path is replaced rather than appended, matching every other call in this client: request
+ /// paths here are absolute — /api/v1/… — so a deployment behind a path prefix is already
+ /// unsupported, and pretending otherwise in this one place would be a difference nobody could act
+ /// on.
+ ///
+ private static Uri EventsUrl(Uri serverUrl) =>
+ new UriBuilder(serverUrl)
+ {
+ Scheme = string.Equals(serverUrl.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)
+ ? "wss"
+ : "ws",
+ Path = VaultEvents.Path,
+ Query = string.Empty,
+ Fragment = string.Empty,
+ }.Uri;
+
+ private static async Task DialAsync(Uri url, string token, CancellationToken cancellationToken)
+ {
+ var socket = new ClientWebSocket();
+
+ try
+ {
+ socket.Options.AddSubProtocol(VaultEvents.SubProtocol);
+
+ // A header rather than the Sec-WebSocket-Protocol smuggling ADR 0004 needs for the relay:
+ // this client is a native application and can set one, and the token here is the ordinary
+ // bearer credential rather than a ticket.
+ socket.Options.SetRequestHeader("Authorization", $"Bearer {token}");
+
+ await socket.ConnectAsync(url, cancellationToken).ConfigureAwait(false);
+
+ return socket;
+ }
+ catch
+ {
+ socket.Dispose();
+ throw;
+ }
+ }
+
+ private void Start()
+ {
+ if (pump is not null)
+ {
+ return;
+ }
+
+ lock (starting)
+ {
+ pump ??= Task.Run(() => RunAsync(closing.Token), closing.Token);
+ }
+ }
+
+ /// Connects, reads until it cannot, waits, and does it again.
+ private async Task RunAsync(CancellationToken cancellationToken)
+ {
+ var backoff = options.InitialBackoff;
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ var outcome = await AttemptAsync(cancellationToken).ConfigureAwait(false);
+
+ // A socket that lived long enough to say hello proves the server is there and willing, so
+ // the next failure starts from the bottom again rather than inheriting the backoff that
+ // got us here. Without this a laptop that woke, connected, and then lost its network an
+ // hour later would wait a full minute before trying, having already proved it need not.
+ if (outcome == Outcome.Established)
+ {
+ backoff = options.InitialBackoff;
+ }
+
+ // The server said this token is spent, which the token provider can fix without waiting.
+ // Reconnecting at once is the whole reason that close code is distinct.
+ var wait = outcome == Outcome.TokenExpired ? TimeSpan.Zero : Jitter(backoff);
+
+ if (wait > TimeSpan.Zero)
+ {
+ try
+ {
+ await Task.Delay(wait, clock, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+
+ backoff = backoff < options.MaxBackoff
+ ? Shorter(backoff * 2, options.MaxBackoff)
+ : options.MaxBackoff;
+ }
+ }
+ }
+
+ /// One connection, from dial to close.
+ private async Task AttemptAsync(CancellationToken cancellationToken)
+ {
+ WebSocket? socket = null;
+
+ try
+ {
+ var token = await tokens.GetAccessTokenAsync(cancellationToken).ConfigureAwait(false);
+
+ socket = await connect(endpoint, token, cancellationToken).ConfigureAwait(false);
+
+ IsConnected = true;
+
+ return await PumpAsync(socket, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return Outcome.Cancelled;
+ }
+ catch (Exception exception) when (exception is not OutOfMemoryException)
+ {
+ // Every failure this can meet — no network, a refused upgrade, a server that has not been
+ // deployed with this feature, a token that cannot be refreshed — has the same remedy, and
+ // none of them is worth telling a user about. The synchronisation timer is still running.
+ return Outcome.Failed;
+ }
+ finally
+ {
+ IsConnected = false;
+ socket?.Dispose();
+ }
+ }
+
+ /// Reads frames until the socket ends or goes quiet.
+ private async Task PumpAsync(WebSocket socket, CancellationToken cancellationToken)
+ {
+ var buffer = new byte[8 * 1024];
+ var silence = options.InitialSilenceTimeout;
+ var established = false;
+
+ while (socket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
+ {
+ // Rebuilt per frame rather than reset, because a linked source cannot be un-cancelled and
+ // the deadline is what detects a socket that has silently gone away.
+ using var deadline = new CancellationTokenSource(silence, clock);
+ using var quiet = CancellationTokenSource.CreateLinkedTokenSource(
+ cancellationToken, deadline.Token);
+
+ WebSocketReceiveResult received;
+
+ try
+ {
+ received = await socket.ReceiveAsync(buffer, quiet.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ // Silent for longer than the server said it would be. The socket is gone in a way that
+ // only reconnecting can discover, which is what a proxy dropping an idle connection
+ // looks like from this end.
+ return Ended(established);
+ }
+
+ if (received.MessageType == WebSocketMessageType.Close)
+ {
+ return (int?)received.CloseStatus == VaultEvents.TokenExpiredCloseCode
+ ? Outcome.TokenExpired
+ : Ended(established);
+ }
+
+ // Binary is reserved by ADR 0012 for shared-session data, and text that arrived in pieces
+ // is longer than anything this protocol defines. Skipped rather than fatal, so a newer
+ // server does not cost this client its push for the whole session.
+ if (received.MessageType != WebSocketMessageType.Text || !received.EndOfMessage)
+ {
+ continue;
+ }
+
+ if (Parse(buffer.AsSpan(0, received.Count)) is not { } frame)
+ {
+ continue;
+ }
+
+ established = true;
+ silence = await AbsorbAsync(socket, frame, silence, cancellationToken).ConfigureAwait(false);
+ }
+
+ return Ended(established);
+ }
+
+ /// Deals with one frame, and says how long the socket may now stay quiet.
+ private async Task AbsorbAsync(
+ WebSocket socket,
+ VaultEvent frame,
+ TimeSpan silence,
+ CancellationToken cancellationToken)
+ {
+ if (frame.HeartbeatSeconds is > 0 and var seconds)
+ {
+ // Three missed heartbeats. Two is within one paused thread of a false positive, and a
+ // false positive here costs a reconnection rather than anything a user sees.
+ silence = TimeSpan.FromSeconds(seconds * 3);
+ }
+
+ if (string.Equals(frame.Kind, VaultEventKinds.Ping, StringComparison.Ordinal))
+ {
+ await socket.SendAsync(
+ JsonSerializer.SerializeToUtf8Bytes(
+ new VaultEvent(VaultEventKinds.Pong), DodoSshJsonContext.Default.VaultEvent),
+ WebSocketMessageType.Text,
+ endOfMessage: true,
+ cancellationToken)
+ .ConfigureAwait(false);
+
+ return silence;
+ }
+
+ // Everything else, including a kind this build has never heard of, goes to the reader — which
+ // is what makes the frame table extensible. An unrecognised kind is one the caller ignores;
+ // refusing it here would be this class deciding what a newer server may say.
+ notices.Writer.TryWrite(frame);
+
+ return silence;
+ }
+
+ private static Outcome Ended(bool established) =>
+ established ? Outcome.Established : Outcome.Failed;
+
+ private static VaultEvent? Parse(ReadOnlySpan utf8)
+ {
+ try
+ {
+ return JsonSerializer.Deserialize(utf8, DodoSshJsonContext.Default.VaultEvent);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ ///
+ /// Spreads reconnections out, so a server that restarts is not met by every client at once.
+ ///
+ ///
+ /// RandomNumberGenerator because System.Random is banned repo-wide. Nothing here is
+ /// security-relevant — the ban exists so that nothing key-, token- or nonce-adjacent can reach for
+ /// the weak one by habit, and paying a few microseconds to keep that rule absolute is the cheaper
+ /// side of the trade.
+ ///
+ private static TimeSpan Jitter(TimeSpan delay)
+ {
+ var milliseconds = (int)Math.Clamp(delay.TotalMilliseconds, 1, int.MaxValue / 2);
+
+ return TimeSpan.FromMilliseconds(
+ milliseconds + RandomNumberGenerator.GetInt32(0, Math.Max(1, milliseconds / 2)));
+ }
+
+ private static TimeSpan Shorter(TimeSpan left, TimeSpan right) => left < right ? left : right;
+
+ /// How one connection attempt ended.
+ private enum Outcome
+ {
+ /// Never got as far as a frame. Back off.
+ Failed,
+
+ /// Ran, and then ended. Back off, but from the bottom.
+ Established,
+
+ /// The server closed it because the token expired. Reconnect at once with a new one.
+ TokenExpired,
+
+ /// The stream is being disposed.
+ Cancelled,
+ }
+}
diff --git a/src/DodoSSH.Client.App/App.axaml.cs b/src/DodoSSH.Client.App/App.axaml.cs
index b336613..1b70943 100644
--- a/src/DodoSSH.Client.App/App.axaml.cs
+++ b/src/DodoSSH.Client.App/App.axaml.cs
@@ -113,7 +113,7 @@ internal sealed partial class DodoSshApp : Application
// computer with a usable TPM gets the store that keeps a device key behind a Windows consent prompt;
// anything else gets one that reports itself unavailable, so unlock keeps asking for the passphrase
// (ADR 0007). The update channel answers the same shape of question about how this copy was
- // installed, and a build run from a checkout likewise gets one that says so. See ADR 0012.
+ // installed, and a build run from a checkout likewise gets one that says so. See ADR 0013.
var deviceKeys = DesktopDeviceKeyStores.ForThisMachine(paths);
var updates = UpdateChannels.ForThisMachine();
diff --git a/src/DodoSSH.Client.App/Platform/VelopackUpdateChannel.cs b/src/DodoSSH.Client.App/Platform/VelopackUpdateChannel.cs
index 8ea2a4b..8b45ae6 100644
--- a/src/DodoSSH.Client.App/Platform/VelopackUpdateChannel.cs
+++ b/src/DodoSSH.Client.App/Platform/VelopackUpdateChannel.cs
@@ -65,7 +65,7 @@ internal static class UpdateChannels
/// DodoSSH.Client.Shell is shared with the Android head, which must never acquire an updater.
///
///
-/// See docs/adr/0012-desktop-distribution-and-updates.md.
+/// See docs/adr/0013-desktop-distribution-and-updates.md.
///
///
internal sealed class VelopackUpdateChannel : IUpdateChannel
diff --git a/src/DodoSSH.Client.App/Program.cs b/src/DodoSSH.Client.App/Program.cs
index dc6d553..ff7ec22 100644
--- a/src/DodoSSH.Client.App/Program.cs
+++ b/src/DodoSSH.Client.App/Program.cs
@@ -54,7 +54,7 @@ internal static class Program
///
/// The profile directory is the right home because Velopack never touches it — the pack id is
/// deliberately not DodoSSH, so the install root and ClientPaths.DataDirectory are
- /// siblings rather than the same folder. See docs/adr/0012-desktop-distribution-and-updates.md.
+ /// siblings rather than the same folder. See docs/adr/0013-desktop-distribution-and-updates.md.
///
///
/// An environment variable rather than the control's own options, because it is read by the WebView2
diff --git a/src/DodoSSH.Client.App/Views/ConfirmDeleteCard.axaml b/src/DodoSSH.Client.App/Views/ConfirmDeleteCard.axaml
index 0d08387..93b1e01 100644
--- a/src/DodoSSH.Client.App/Views/ConfirmDeleteCard.axaml
+++ b/src/DodoSSH.Client.App/Views/ConfirmDeleteCard.axaml
@@ -41,6 +41,21 @@
Text="{Binding PendingDeletion.Usage}" />
+
+
+
+
+
diff --git a/src/DodoSSH.Client.App/Views/HostDrawer.axaml b/src/DodoSSH.Client.App/Views/HostDrawer.axaml
index 24b4813..5dc6afd 100644
--- a/src/DodoSSH.Client.App/Views/HostDrawer.axaml
+++ b/src/DodoSSH.Client.App/Views/HostDrawer.axaml
@@ -55,10 +55,11 @@
renderer. They are listed in docs/design-import-gaps.md with what ships instead, and none of them is
drawn disabled.
- The design's fifth missing control was the vault picker's chevron, and half of it now exists: a host
- being *created* is asked which vault it goes into, in the editor below. What still does not exist is
- the other half — moving an existing host — because the two vaults are encrypted under different keys,
- so that is a delete and a retype rather than an edit.
+ The design's fifth missing control was the vault picker's chevron, and both halves of what it stood for
+ now exist without it: a host being *created* is asked which vault it goes into, in the editor below, and
+ an existing one is moved from the pane's ⋯ menu. The chevron itself stays undrawn, because a chevron on
+ a subtitle implies an edit and this is not one — the two vaults are encrypted under different keys, so a
+ move is a re-seal into one and a tombstone in the other, and the host takes a new id.
-->
@@ -91,10 +93,15 @@
+
+
diff --git a/src/DodoSSH.Client.App/Views/HostsScreen.axaml.cs b/src/DodoSSH.Client.App/Views/HostsScreen.axaml.cs
index e291c2e..07fc0f5 100644
--- a/src/DodoSSH.Client.App/Views/HostsScreen.axaml.cs
+++ b/src/DodoSSH.Client.App/Views/HostsScreen.axaml.cs
@@ -96,6 +96,11 @@ internal sealed partial class HostsScreen : UserControl
HostGrid.AddHandler(PointerPressedEvent, OnPointerPressed, RoutingStrategies.Tunnel);
HostGrid.AddHandler(ContextRequestedEvent, OnContextRequested, RoutingStrategies.Tunnel);
+ // And the group cards answer a right click the same way, for the same reason: their menu's commands
+ // read the vault's group selection, and without this they would act on whichever card was selected
+ // before — or, with none, on the group the trail ends with, which is not on screen at all.
+ GroupGrid.AddHandler(ContextRequestedEvent, OnGroupContextRequested, RoutingStrategies.Tunnel);
+
HostGrid.PointerMoved += OnPointerMoved;
HostGrid.PointerReleased += OnPointerReleased;
HostGrid.PointerCaptureLost += OnPointerCaptureLost;
@@ -204,6 +209,33 @@ internal sealed partial class HostsScreen : UserControl
vault.SelectedSidebarRow = row;
}
+ ///
+ /// Points the group menu at whatever was right-clicked.
+ ///
+ ///
+ ///
+ /// The host grid's rule, applied to the cards above it — see . What is
+ /// different is what an unaimed menu would have done: GroupTarget falls back to the open group
+ /// when no card is selected, so Edit and Delete over a card would have been offered about the group whose
+ /// contents are showing rather than the one the pointer is on. This menu is the only way to either of
+ /// them now, so aiming it is the whole of aiming them.
+ ///
+ ///
+ /// Cancelled outright over the space around the cards, as the host grid's is. That is not a group, and
+ /// the fallback is exactly what would make the menu look like it worked there.
+ ///
+ ///
+ private void OnGroupContextRequested(object? sender, ContextRequestedEventArgs e)
+ {
+ if (Vault is not { } vault || RowUnder(e.Source) is not HostGroupRowViewModel row)
+ {
+ e.Handled = true;
+ return;
+ }
+
+ vault.SelectedGroup = row;
+ }
+
///
/// Remembered rather than acted on. Whether this press is a click or the start of a drag is not known
/// until the pointer moves, so this is the point at which both are still possible.
diff --git a/src/DodoSSH.Client.Session/ServerConnection.cs b/src/DodoSSH.Client.Session/ServerConnection.cs
index 9b7370b..d89890a 100644
--- a/src/DodoSSH.Client.Session/ServerConnection.cs
+++ b/src/DodoSSH.Client.Session/ServerConnection.cs
@@ -150,6 +150,17 @@ public interface IVaultServer : IDisposable
/// Vault key grants: who can open a vault, and who let them.
IVaultGrantApi Grants { get; }
+ ///
+ /// Notices that something changed, so a synchronisation need not wait for the timer.
+ ///
+ ///
+ /// Always present, never null: a server that does not offer the feature — or a test standing in
+ /// for one — supplies , which simply never delivers. That keeps
+ /// every caller on one shape, because the correct behaviour without a socket is the behaviour
+ /// with a silent one: synchronise on the timer. See ADR 0012.
+ ///
+ IVaultEventStream Events { get; }
+
/// Obtains the identity provider's signature over a key statement.
IKeyBindingAuthorizer KeyBinding { get; }
@@ -197,7 +208,8 @@ public sealed class ServerConnection : IVaultServer
MetaResponse meta,
OidcClient oidc,
RefreshingAccessTokenProvider tokens,
- DodoSshApiClient api)
+ DodoSshApiClient api,
+ TimeProvider clock)
{
ServerUrl = serverUrl;
this.http = http;
@@ -206,6 +218,14 @@ public sealed class ServerConnection : IVaultServer
Oidc = oidc;
this.tokens = tokens;
Api = api;
+
+ // Decided from what this server said it supports rather than attempted and allowed to fail,
+ // which is the same capability negotiation SyncOptions below does — see ADR 0002. A client
+ // that dialled anyway would reconnect against a 404 for the whole session, and would look
+ // from the outside exactly like one whose network was eating WebSockets.
+ Events = meta.Features.Contains(VaultEvents.Feature, StringComparer.Ordinal)
+ ? new VaultEventStream(serverUrl, tokens, clock)
+ : IdleVaultEventStream.Instance;
}
/// The server this is connected to.
@@ -238,6 +258,9 @@ public sealed class ServerConnection : IVaultServer
///
public IVaultGrantApi Grants => Api;
+ ///
+ public IVaultEventStream Events { get; }
+
///
public IKeyBindingAuthorizer KeyBinding => Oidc;
@@ -311,7 +334,8 @@ public sealed class ServerConnection : IVaultServer
meta,
oidc,
refreshing,
- new DodoSshApiClient(transport, refreshing));
+ new DodoSshApiClient(transport, refreshing),
+ clock);
}
catch
{
@@ -382,7 +406,8 @@ public sealed class ServerConnection : IVaultServer
meta,
oidc,
refreshing,
- new DodoSshApiClient(transport, refreshing));
+ new DodoSshApiClient(transport, refreshing),
+ clock);
}
catch
{
@@ -400,6 +425,12 @@ public sealed class ServerConnection : IVaultServer
}
disposed = true;
+
+ // First, and without waiting: the socket's own loops read the token provider and the transport
+ // below, so tearing either down while it is still dialling would surface as a fault on a
+ // background thread at the moment a user signed out.
+ Events.Dispose();
+
tokens.Dispose();
http.Dispose();
}
diff --git a/src/DodoSSH.Client.Shell/ViewModels/VaultViewModel.cs b/src/DodoSSH.Client.Shell/ViewModels/VaultViewModel.cs
index 1340856..ef68f96 100644
--- a/src/DodoSSH.Client.Shell/ViewModels/VaultViewModel.cs
+++ b/src/DodoSSH.Client.Shell/ViewModels/VaultViewModel.cs
@@ -10,6 +10,7 @@ using DodoSSH.Client.Session;
using DodoSSH.Client.Ssh;
using DodoSSH.Client.Sync;
using DodoSSH.Client.Terminal;
+using DodoSSH.Contracts;
namespace DodoSSH.Client.Shell.ViewModels;
@@ -39,29 +40,70 @@ internal interface ISidebarRow;
internal sealed record SidebarGroupHeader(Guid? GroupId, string Label, int Count, bool IsExpanded)
: ISidebarRow
{
+ ///
+ /// The vault this heading's group lives in, or empty where there is only one vault to be in.
+ ///
+ ///
+ /// The one thing a heading could not say while the headings were one vault's. Two vaults may each hold
+ /// a group called "production" — they are separate folders under separate keys — and a list with one
+ /// heading per group has nothing else to tell them apart with. Decided by the list rather than the row,
+ /// for the reason is.
+ ///
+ internal string VaultBadge { get; init; } = string.Empty;
+
+ /// Whether this heading has a vault to name.
+ internal bool HasVaultBadge => VaultBadge.Length > 0;
+
/// The chevron, as text, because the heading is drawn in the list's own item template.
internal string Chevron => IsExpanded ? "▾" : "▸";
}
+/// One group as it came out of a vault, with the vault it came out of.
+///
+/// The pair the group reload hands the group rebuild, and the vault half of it is what makes a group a
+/// shared thing rather than a private one: a rename and a delete both have to go back to the vault the group
+/// is in, and the row that offers them is drawn from a list that now spans every readable vault.
+///
+/// The group, decrypted.
+/// The vault it lives in.
+/// That vault's display name.
+internal sealed record VaultGroupItem(VaultItem Item, Guid VaultId, string VaultName);
+
/// One group, as a row in the group list.
///
/// Thinner than the other row types because a group is thinner: a name, and how many hosts name it. The
/// count is computed from the host list rather than stored on the group — see
/// for why membership lives on the host — so it is passed in rather than read off the item.
///
-internal sealed class HostGroupRowViewModel(VaultItem group, int hostCount)
+internal sealed class HostGroupRowViewModel(VaultGroupItem group, int hostCount)
{
- internal Guid EntityId => group.EntityId;
+ internal Guid EntityId => group.Item.EntityId;
- internal HostGroupSecret Group => group.Secret;
+ /// Which vault this group lives in. See .
+ internal Guid VaultId => group.VaultId;
- internal string Label => group.Secret.Label;
+ /// The vault's display name.
+ internal string VaultName => group.VaultName;
+
+ ///
+ /// The vault name to print on this card, or empty when there is only one vault to be in.
+ ///
+ ///
+ internal string VaultBadge { get; init; } = string.Empty;
+
+ /// Whether this row has a vault to name.
+ internal bool HasVaultBadge => VaultBadge.Length > 0;
+
+ internal HostGroupSecret Group => group.Item.Secret;
+
+ internal string Label => group.Item.Secret.Label;
internal int HostCount => hostCount;
- internal bool IsReadOnly => group.IsReadOnly;
+ internal bool IsReadOnly => group.Item.IsReadOnly;
- internal string Badge => ItemBadge.For(group.IsBlocked, group.IsReadOnly, group.HasUnsyncedChanges);
+ internal string Badge =>
+ ItemBadge.For(group.Item.IsBlocked, group.Item.IsReadOnly, group.Item.HasUnsyncedChanges);
/// What the row says under the name.
internal string Description => hostCount == 1 ? "1 host" : $"{hostCount} hosts";
@@ -941,6 +983,27 @@ internal sealed record DeletionRequest(
{
/// Whether anything depends on the item, which is the line worth reading twice.
internal bool HasUsage => Usage.Length > 0;
+
+ ///
+ /// The second question this deletion has to ask, or empty where it has none.
+ ///
+ ///
+ ///
+ /// Only a group has one, and it is the one deletion in this application whose scope is not decided by
+ /// what is being deleted: a group is a heading, and the machines under it may be the reason the heading
+ /// existed or may be forty perfectly good hosts that want a different shelf. Nothing here can tell which,
+ /// so it is asked — see , which is the answer.
+ ///
+ ///
+ /// A sentence rather than a flag, because the card that draws it is shared by six kinds of deletion and
+ /// must not grow a branch per kind. Empty is "there is no second question", which is also what a group
+ /// with nothing filed under it gets.
+ ///
+ ///
+ internal string Choice { get; init; } = string.Empty;
+
+ /// Whether this deletion has a second question to put.
+ internal bool HasChoice => Choice.Length > 0;
}
///
@@ -1025,13 +1088,29 @@ internal sealed partial class VaultViewModel(
VaultVisibility? visibility = null) : ObservableObject, IAsyncDisposable
{
///
+ ///
/// A minute. The pull is a delta keyed on a cursor, so an idle pass is one small request and costs the
/// server almost nothing; the number that matters is how stale a teammate's change may look, and a
/// minute is short enough not to be noticed. Anything much shorter would be polling for its own sake,
/// and a change made on this machine does not wait for the timer anyway — saving pushes immediately.
+ ///
+ ///
+ /// Unchanged by the push channel, and deliberately so. The socket makes a pass early; this is
+ /// what makes one happen at all, for a client whose network eats WebSockets, whose server has the
+ /// feature off, or whose notice was dropped. See and ADR 0012.
+ ///
///
private static readonly TimeSpan AutoSyncInterval = TimeSpan.FromMinutes(1);
+ /// How long a pushed notice waits, in case more are on their way.
+ ///
+ /// A quarter of a second, which is below what anybody perceives and above the gap between the
+ /// notices one person's save produces — a host and its activity log entry are two items in one
+ /// push, and a colleague clearing a folder is a burst. Without it each notice would run its own
+ /// full pass, and the pass a burst deserves is one.
+ ///
+ private static readonly TimeSpan NoticeDebounce = TimeSpan.FromMilliseconds(250);
+
/// How often the logs are pruned, at most.
///
/// Hours rather than minutes, because pruning writes tombstones that sync. Retention is measured in days
@@ -1047,13 +1126,15 @@ internal sealed partial class VaultViewModel(
private readonly SemaphoreSlim syncGate = new(1, 1);
///
- /// The groups as they came out of the vault, before the host counts are attached.
+ /// The groups as they came out of the vaults, before the host counts are attached.
///
///
/// Held between the group reload and the host reload, which are two passes because a group row says how
- /// many hosts name it and the hosts are read second. See .
+ /// many hosts name it and the hosts are read second. See . Every readable
+ /// vault's, each entry carrying which one it came from — a group is shared by being in a shared vault,
+ /// so the vault has to travel with it as far as the row that renames and deletes it.
///
- private IReadOnlyList> groupItems = [];
+ private IReadOnlyList groupItems = [];
///
/// The same groups by id, which is the shape the inheritance walk takes.
@@ -1365,6 +1446,14 @@ internal sealed partial class VaultViewModel(
[ObservableProperty]
private VaultChoiceViewModel? selectedTargetVault;
+ ///
+ /// The host card that is selected, or null when none is.
+ ///
+ ///
+ /// The application's selection, which everything that acts on a host reads — connecting, editing,
+ /// deleting. It shares one selection with : selecting a host takes the
+ /// mark off a group card and the other way about. See .
+ ///
[ObservableProperty]
private HostRowViewModel? selectedHost;
@@ -1392,8 +1481,14 @@ internal sealed partial class VaultViewModel(
/// The group card that is selected, or null when none is.
///
///
+ ///
/// One click, and nothing more than a highlight: it is what the group's own EDIT and DELETE act on. What
/// it deliberately no longer does is narrow the grid — see .
+ ///
+ ///
+ /// It shares one selection with . Setting either clears the other, so
+ /// exactly one card on the screen is ever lit. See .
+ ///
///
[ObservableProperty]
private HostGroupRowViewModel? selectedGroup;
@@ -1409,7 +1504,7 @@ internal sealed partial class VaultViewModel(
///
///
/// Separate from , and no longer sets it. The two answer different
- /// questions — "what is on screen" and "what would EDIT and DELETE act on" — and while one click meant
+ /// questions — "what is on screen" and "which card is chosen" — and while one click meant
/// both there was no way to name a group without also narrowing the grid to it. Two gestures, two
/// properties; is where the two meet.
///
@@ -1467,11 +1562,49 @@ internal sealed partial class VaultViewModel(
/// What the group's parent picker offers: "no parent", then every group that may legally be one.
///
///
+ ///
+ /// One vault's, and the one this group is going into — see . A
+ /// parent in another vault would be a group half the people holding this one's key cannot resolve, and
+ /// the tree they see would be missing a level nobody can point at.
+ ///
internal ObservableCollection GroupEditorParentChoices { get; } = [];
[ObservableProperty]
private GroupChoice? groupEditorSelectedParent;
+ ///
+ /// Which vault a group being created will be filed into.
+ ///
+ ///
+ ///
+ /// The same picker the host editor has, on the form beside it, and for the same reason: this is the
+ /// decision that makes the thing shared, it cannot be changed by saving, and the only other
+ /// control that could have answered it is a standing preference on a different screen. A group is where
+ /// hosts are filed and what lends them a port, a username and a key — so putting one in a shared vault is
+ /// how a team gets an arrangement rather than twenty machines in a heap, which is most of what sharing is
+ /// for.
+ ///
+ ///
+ /// Changed afterwards it can be, by , which is a separate act for the reason
+ /// moving a host is: it re-seals the group, everything nested inside it and every host filed under them
+ /// into a second vault's key, and nothing that happens as a side effect of pressing SAVE on a form should
+ /// be that.
+ ///
+ ///
+ /// Filled from , so it offers what every other "file this into" control does:
+ /// vaults this session can both read and write.
+ ///
+ ///
+ internal ObservableCollection GroupEditorVaultChoices { get; } = [];
+
+ [ObservableProperty]
+ private VaultChoiceViewModel? groupEditorSelectedVault;
+
+ /// Whether the editor should be asking which vault this group goes into.
+ ///
+ internal bool ShowsGroupEditorVaultChoice =>
+ EditingGroupId is null && GroupEditorVaultChoices.Count > 1;
+
/// What the group's authentication picker offers, for the hosts beneath it.
///
/// The host picker's list without its first entry. A group cannot default to "ask for a password each
@@ -1486,8 +1619,33 @@ internal sealed partial class VaultViewModel(
/// The group being renamed, or null when the box would create one.
[ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(ShowsGroupEditorVaultChoice))]
private Guid? editingGroupId;
+ ///
+ /// Which vault the group editor will write to, or null until an editor has been opened.
+ ///
+ ///
+ /// Nullable where is not, because the group name box is bound whether
+ /// or not anything raised an editor over it — that is what the desktop's group bar was, and typing a
+ /// name into it and pressing ADD is still a way to make a group. is
+ /// what answers for that case, and it answers with the standing preference: a group made without
+ /// choosing a vault is a new item like any other.
+ ///
+ private Guid? editingGroupVaultId;
+
+ /// The vault the group editor writes to, whether or not one was ever chosen for it.
+ private Guid GroupEditorVaultId => editingGroupVaultId ?? TargetVaultId;
+
+ ///
+ /// The name of the vault a group being renamed is in, for the drawer's header, or empty.
+ ///
+ ///
+ /// Kept rather than looked up per redraw, and empty wherever there is only one vault to be in — the
+ /// same rule the badges follow, because a header naming the only vault there is says nothing.
+ ///
+ private string editingGroupVaultName = string.Empty;
+
[ObservableProperty]
private SshKeyRowViewModel? selectedKey;
@@ -1817,8 +1975,92 @@ internal sealed partial class VaultViewModel(
/// while the deletion question is up it would offer to ask it again — which is the rule
/// has always carried for the row of buttons these two replaced. The
/// question takes CONNECT's place in the footer for the same reason it took DELETE's.
+ ///
+ /// The move panel is in that list too and for the same reason. It takes the footer as well, so leaving
+ /// CONNECT under it would put two things in one row — and the menu it came from would still be offering
+ /// to open it.
+ ///
///
- internal bool ShowsHostPaneActions => IsShowingHostDetail && !IsConfirmingHostDeletion;
+ internal bool ShowsHostPaneActions =>
+ IsShowingHostDetail && !IsConfirmingHostDeletion && !IsMovingHost;
+
+ ///
+ /// Whether the panel asking which vault to move the selected host to is up.
+ ///
+ ///
+ /// The armed-state idiom this window uses everywhere instead of a modal, and here it carries a choice
+ /// rather than a yes: the question is not "are you sure" but "which vault", and the sentence beside it
+ /// says what will be left behind. See .
+ ///
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(ShowsHostPaneActions))]
+ private bool isMovingHost;
+
+ /// Which host the open move panel is about. Null when it is closed.
+ ///
+ /// Held rather than read off the selection, so the panel survives a reload replacing every row object —
+ /// see , which is the only thing that reads it.
+ ///
+ private Guid? movingHostId;
+
+ /// Where the selected host could be moved: every vault this session can write to but its own.
+ internal ObservableCollection MoveVaultChoices { get; } = [];
+
+ [ObservableProperty]
+ private VaultChoiceViewModel? selectedMoveVault;
+
+ ///
+ /// Whether the selected host has anywhere to move to.
+ ///
+ ///
+ ///
+ /// Asked so the phone can leave the button out rather than offer one that answers with a refusal — it
+ /// has room for two buttons under a host and no room to explain a third that does nothing. The desktop
+ /// keeps its menu entry either way: a menu that grew and shrank would be a menu whose items move.
+ ///
+ ///
+ /// It counts vaults rather than merely asking whether there are two, because the answer is per host: a
+ /// host already in the only other writable vault has nowhere to go, and a read-only vault is not
+ /// somewhere anything can be moved to.
+ ///
+ ///
+ internal bool CanMoveSelectedHost =>
+ SelectedHost is { IsReadOnly: false } row
+ && session.ReadableVaults.Any(vault => vault.CanWrite && vault.VaultId != row.VaultId);
+
+ ///
+ /// Whether the panel asking which vault to move the group to is up.
+ ///
+ ///
+ ///
+ /// The host's panel again — see — under the GROUPS heading rather than in the
+ /// drawer, because a group has no drawer of its own: the pane beside this screen is about one machine.
+ ///
+ ///
+ /// It has no ShowsGroupActions to turn off, and does not need one. A group's actions are the
+ /// card's right-click menu now, which is not on screen while this panel is: opening it is what draws it.
+ /// The deletion question below it is disarmed by and folds this away in return,
+ /// so the section shows at most one of the two.
+ ///
+ ///
+ [ObservableProperty]
+ private bool isMovingGroup;
+
+ /// Which group the open move panel is about. Null when it is closed.
+ ///
+ private Guid? movingGroupId;
+
+ /// Where the group could be moved: every vault this session can write to but its own.
+ internal ObservableCollection MoveGroupVaultChoices { get; } = [];
+
+ [ObservableProperty]
+ private VaultChoiceViewModel? selectedMoveGroupVault;
+
+ // There is deliberately no CanMoveGroup to match CanMoveSelectedHost. That one exists so the phone can
+ // leave a button out rather than draw one that answers with a refusal; a group is reached through the
+ // card's right-click menu, which is not drawn until it is opened and whose entries do not move. The one
+ // place the question decides anything is MoveGroup, which asks it by building the picker and saying so
+ // when it comes back empty.
///
/// What the drawer's header says it is about.
@@ -1839,14 +2081,25 @@ internal sealed partial class VaultViewModel(
/// The line under it: which keychain this is filed in, or what a group is for.
///
///
- /// The vault's name and not a picker for it, although the design draws one with a chevron. An item
- /// cannot be moved between vaults here — that is a delete and a retype, because the two are encrypted
- /// under different keys — so a control offering the move would be offering something no layer below
- /// this can do. Where a *new* item goes is chosen on the keychain screen's own picker; see
- /// .
+ ///
+ /// The vault's name and not a picker for it, although the design draws one with a chevron. A host and a
+ /// group can both be moved between vaults — see and — but
+ /// not from here and not by saving: the two vaults are encrypted under different keys, so a move is a
+ /// re-seal into one and a tombstone in the other, and every item involved takes a new id. A chevron on a
+ /// subtitle implies an edit and would be describing something else. Where a *new* item goes is chosen in
+ /// the editor's own picker; see
+ ///
+ ///
+ /// A group being renamed says its vault here for the same reason a host being edited does, and it is
+ /// the only line that says it: the picker is hidden for an existing group, and renaming a colleague's
+ /// shelf without being told whose it is is exactly the edit worth naming. A group being *made* says
+ /// what a group is for instead, because the picker under it is already answering "which vault".
+ ///
///
internal string DrawerSubtitle => (IsEditing, IsEditingGroup) switch
{
+ (_, true) when EditingGroupId is not null && editingGroupVaultName.Length > 0 =>
+ editingGroupVaultName,
(_, true) => "A heading, and what its hosts inherit",
(true, _) when editingEntityId is null => SelectedTargetVault?.Name ?? string.Empty,
_ => SelectedHost?.VaultName ?? string.Empty,
@@ -1961,9 +2214,10 @@ internal sealed partial class VaultViewModel(
///
///
/// Only while creating, and only where there is more than one vault to choose between. An existing
- /// host's vault is not editable and the picker is not shown disabled beside it: the two are encrypted
- /// under different keys, so moving an item is a delete and a retype rather than a save — see the note
- /// on the drawer's header, which says where the host is filed.
+ /// host's vault is not a field of this form and the picker is not shown disabled beside it: the two
+ /// are encrypted under different keys, so moving one is a re-seal and a tombstone rather than a save.
+ /// That is offered — by , from the pane's own menu — and it is a separate act
+ /// precisely because it must not happen as a side effect of saving something else.
///
///
/// Hidden at one vault rather than shown with a single option, which is the rule
@@ -2385,6 +2639,26 @@ internal sealed partial class VaultViewModel(
[ObservableProperty]
private DeletionRequest? pendingDeletion;
+ ///
+ /// The answer to : whether a group's hosts go with it.
+ ///
+ ///
+ ///
+ /// Off is the answer that keeps the machines, and it is off by default and reset to off on every
+ /// question — see . A tick left standing from the last group
+ /// deleted would delete forty hosts on behalf of somebody who was only tidying a heading away, and there
+ /// is no undo on either side of it.
+ ///
+ ///
+ /// A tick rather than a pair of options, and deliberately not two equally weighted answers: they are not
+ /// equally weighted. Keeping the hosts is recoverable — they turn up under UNGROUPED and can be filed
+ /// again — and deleting them is not, so the safe answer is the one that needs no decision and the
+ /// destructive one is the one that has to be reached for.
+ ///
+ ///
+ [ObservableProperty]
+ private bool deletionTakesTheHostsToo;
+
internal bool IsConfirmingDeletion => PendingDeletion is not null;
/// Whether the sidebar's row of host buttons is showing.
@@ -2410,26 +2684,23 @@ internal sealed partial class VaultViewModel(
internal bool IsConfirmingGroupDeletion => PendingDeletion?.Target is DeletionTarget.Group;
///
- /// What the group panel's EDIT and DELETE act on: the card that is selected, or the group that is open.
+ /// What a group command with no argument acts on: the card that is selected, or the group that is open.
///
///
- /// Two answers, because a card is no longer where the user is. Selecting one aims the buttons at it,
- /// which is what a click has always done; with nothing selected they aim at the group whose contents are
- /// on screen — the one the trail ends with. Without that fallback a group with no groups inside it could
- /// be opened and then never edited, because opening a group is exactly what takes its own card off the
- /// screen. It is also what a file manager does: act on the selection, and on the current folder when
- /// there is none.
+ /// Two answers, because a card is no longer where the user is. Selecting one aims at it, which is what a
+ /// click has always done; with nothing selected the answer is the group whose contents are on screen —
+ /// the one the trail ends with. That fallback is what makes + NEW HOST open on the group somebody is
+ /// standing in rather than on none, and it is what a file manager does: act on the selection, and on the
+ /// current folder when there is none.
+ ///
+ /// The desktop's Edit and Delete reach this through the card menu, which selects whatever was
+ /// right-clicked first, so the fallback is not what they read — see HostsScreen.OnGroupContextRequested.
+ /// They used to be a pair of buttons beside the GROUPS heading, which had no card under a pointer to
+ /// mean and so leaned on it.
+ ///
///
internal HostGroupRowViewModel? GroupTarget => SelectedGroup ?? GroupFilter;
- /// Whether the group panel's buttons are showing.
- ///
- /// Hidden with nothing to act on as well as while the question is up. A pair of buttons over a grid of
- /// cards nobody has chosen between is a pair whose subject the user has to work out, and the answer
- /// would be "neither" — see .
- ///
- internal bool ShowsGroupActions => GroupTarget is not null && !IsConfirmingGroupDeletion;
-
/// Whether this vault has any groups, which is what makes the sidebar draw headings.
internal bool HasGroups => Groups.Count > 0;
@@ -2863,9 +3134,7 @@ internal sealed partial class VaultViewModel(
Hosts.Add(host);
}
- // Selection survives a reload. Losing it on every sync would move the terminal's target out from
- // under the user.
- SelectedHost = Hosts.FirstOrDefault(row => row.EntityId == selectedId) ?? Hosts.FirstOrDefault();
+ SelectedHost = SelectionAfterReload(selectedId);
// Both, in this order: the group rows carry a host count, and the sidebar's headings are built from
// the group rows.
@@ -2875,6 +3144,25 @@ internal sealed partial class VaultViewModel(
return unreadable;
}
+ /// Which host a freshly filled leaves selected.
+ /// Whatever was selected before the list was refilled.
+ ///
+ ///
+ /// The selection survives a reload, because losing it on every sync would move the terminal's target out
+ /// from under the user. The first host is the fallback rather than nothing, so that a fresh unlock has
+ /// something under CONNECT.
+ ///
+ ///
+ /// That fallback is skipped while a group card holds the selection, and it has to be: the two grids
+ /// share one mark — see — so a sync that invented a host would
+ /// quietly unselect a group nobody had touched, once a minute. Read before
+ /// runs, which is where is re-resolved against the rows this pass makes.
+ ///
+ ///
+ private HostRowViewModel? SelectionAfterReload(Guid? selectedId) =>
+ Hosts.FirstOrDefault(row => row.EntityId == selectedId)
+ ?? (SelectedGroup is null ? Hosts.FirstOrDefault() : null);
+
/// How many buckets would not decrypt.
///
/// The selection survives a reload and a reload never invents one, as the key and credential lists do and
@@ -3007,42 +3295,35 @@ internal sealed partial class VaultViewModel(
/// , which is where the two meet.
///
///
- /// Two reads, and they cover different vaults on purpose. The editable list — the rows the
- /// sidebar draws headings from and the group editor renames — is the active vault's alone. The
- /// resolution map is every readable vault's.
+ /// Three shapes of the same read, and every one of them spans every readable vault. The editable
+ /// list is what the cards and the headings are drawn from and what the editor renames; the per-vault
+ /// lists are what a picker offers, because a picker is always asking about one vault; the map is what a
+ /// host's GroupId resolves through.
///
///
- /// The list stays narrow for the reasons it always did: a row shown across vaults has to carry which
- /// vault it lives in, because rename and delete both need it, and two vaults may hold groups with the
- /// same name, which the one-heading-per-group layout cannot tell apart. Both are worth doing and neither
- /// is a merge's business. Recorded in docs/design-import-gaps.md.
+ /// The list stopped being the active vault's, which is what makes a group shareable. It was
+ /// narrow because a row shown across vaults has to carry the vault it lives in — a rename and a delete
+ /// both need it — and because two vaults may hold groups with the same name, which a list with one
+ /// heading per group cannot tell apart. Both are now paid for rather than avoided: the row carries the
+ /// vault, and the badge beside the name says which. Until it did, a group a colleague made in a shared
+ /// vault had no card, no heading and no way to be corrected from the machine looking straight at the
+ /// hosts filed under it.
///
///
- /// The map could not stay narrow, and that changed with inheritance. While a group was only a
- /// name, a host in a team's vault whose group this did not read appeared under UNGROUPED and lost
- /// nothing else — the same thing the sidebar shows for a group that has been deleted. Since a group
- /// began lending a port, a username and a binding, the same omission silently drops all three: that host
- /// would dial 22 as nobody, while the machine it names is on 2222 as deploy, and nothing on
- /// screen would say why. A missing heading is cosmetic; a missing port is a connection to the wrong
- /// place.
- ///
- ///
- /// Widening the map costs nothing the narrow list was protecting. Group ids are UUIDv7 and unique across
- /// vaults, so there is no name collision to resolve here and no vault to carry — the map is only ever
- /// asked "what does this id say", which is exactly the question a host's GroupId poses.
+ /// The map was widened first, and it had to be, which is why it is separate. While a group was
+ /// only a name, a host in a team's vault whose group this did not read appeared under UNGROUPED and lost
+ /// nothing else. Since a group began lending a port, a username and a binding, the same omission
+ /// silently drops all three: that host would dial 22 as nobody, while the machine it names is on 2222 as
+ /// deploy. So the map answers "what does this id say" for every vault, including the ones
+ /// is keeping off the screen — hiding a vault must never change what a host
+ /// dials, and the list is where hiding is applied. See .
///
///
private async Task ReloadGroupsAsync(CancellationToken cancellationToken)
{
var unreadable = 0;
var resolvable = new Dictionary();
-
- // Emptied before the loop rather than assigned inside it, because the active vault may not be in
- // the readable set at all — a grant withdrawn mid-session is exactly that — and a loop that only
- // ever writes on a match would leave the last readable vault's groups on screen as though they were
- // still this one's.
- groupItems = [];
-
+ var items = new List();
var perVault = new Dictionary>();
foreach (var vault in session.ReadableVaults)
@@ -3056,6 +3337,8 @@ internal sealed partial class VaultViewModel(
foreach (var group in listing.Items)
{
resolvable[group.EntityId] = group.Secret;
+
+ items.Add(new VaultGroupItem(group, vault.VaultId, vault.Name));
}
perVault[vault.VaultId] =
@@ -3064,14 +3347,19 @@ internal sealed partial class VaultViewModel(
.OrderBy(group => group.Secret.Label, StringComparer.CurrentCulture)
.Select(group => new GroupChoice(group.EntityId, group.Secret.Label)),
];
-
- if (vault.VaultId == session.ActiveVaultId)
- {
- groupItems =
- [.. listing.Items.OrderBy(group => group.Secret.Label, StringComparer.CurrentCulture)];
- }
}
+ // Ordered here rather than in the rebuild, and by the same three keys the host and key lists use:
+ // the vault new items go into first, then by vault name, then by label inside each. Two vaults may
+ // hold a group with the same name and both are drawn; which vault it is in is what tells them apart.
+ groupItems =
+ [
+ .. items
+ .OrderByDescending(entry => entry.VaultId == session.ActiveVaultId)
+ .ThenBy(entry => entry.VaultName, StringComparer.CurrentCulture)
+ .ThenBy(entry => entry.Item.Secret.Label, StringComparer.CurrentCulture),
+ ];
+
groupsById = resolvable;
groupsByVault = perVault;
@@ -3188,21 +3476,40 @@ internal sealed partial class VaultViewModel(
groupId is { } id && groupsById.TryGetValue(id, out var group) ? group.Label : string.Empty;
/// Refills , counting the hosts filed under each.
+ ///
+ /// Where a hidden vault's groups are dropped, and the only place they are. The reload above keeps
+ /// every readable vault's, because the map built beside them decides what a host dials; this is the list
+ /// a person looks at, and a card for a vault whose forty hosts have been switched off is a folder that
+ /// cannot be opened onto anything. Dropping them here rather than at the read is what keeps the two
+ /// answers apart. See .
+ ///
private void RebuildGroups()
{
var selectedId = SelectedGroup?.EntityId;
var filteredId = GroupFilter?.EntityId;
+ // The same test the host rows are badged by, and it counts the vaults this session can read rather
+ // than the ones with a group in them: a badge that appeared the moment a colleague made their first
+ // group would be a column arriving on its own.
+ var several = session.ReadableVaults.Take(2).Count() > 1;
+
Groups.Clear();
- foreach (var group in groupItems)
+ foreach (var group in groupItems.Where(entry => IsVaultShown(entry.VaultId)))
{
// Counted over the shown vaults rather than over every host, so a card cannot claim members the
// grid beside it is not drawing. Not counted over VisibleHosts, which would be both too early —
// that list is rebuilt after this — and wrong: a card must not lose members to the search box.
- var count = Hosts.Count(row => row.Host.GroupId == group.EntityId && IsVaultShown(row.VaultId));
+ var count = Hosts.Count(
+ row => row.Host.GroupId == group.Item.EntityId && IsVaultShown(row.VaultId));
- Groups.Add(new HostGroupRowViewModel(group, count));
+ Groups.Add(new HostGroupRowViewModel(group, count)
+ {
+ // Only when there is something to tell apart, as on a host card — and it matters more here,
+ // because two vaults may each hold a "production" and the cards would otherwise be two
+ // identical folders side by side.
+ VaultBadge = several ? group.VaultName.ToUpperInvariant() : string.Empty,
+ });
}
// Re-resolved by id rather than kept: every row object here is replaced on every reload, so an open
@@ -3436,41 +3743,57 @@ internal sealed partial class VaultViewModel(
foreach (var group in Groups)
{
- AddSection(group.EntityId, group.Label, host => host.Host.GroupId == group.EntityId);
+ AddSidebarSection(shown, group, host => host.Host.GroupId == group.EntityId);
}
- AddSection(
+ AddSidebarSection(
+ shown,
null,
- "UNGROUPED",
host => host.Host.GroupId is not { } id || !known.Contains(id),
onlyWhenOccupied: true);
+ }
- void AddSection(
- Guid? groupId,
- string label,
- Func belongs,
- bool onlyWhenOccupied = false)
+ /// Adds one heading to the sidebar, and the hosts under it when it is not folded away.
+ /// The hosts that survived the filters, which every section draws its members from.
+ ///
+ /// The group this heading is for, or null for the ungrouped one. The row rather than its id and label,
+ /// because a heading now says which vault the group is in as well — and null has no vault to name, since
+ /// it is every vault's unfiled hosts at once.
+ ///
+ /// Which of the shown hosts fall under it.
+ /// Whether an empty section is left out altogether.
+ private void AddSidebarSection(
+ IReadOnlyList shown,
+ HostGroupRowViewModel? group,
+ Func belongs,
+ bool onlyWhenOccupied = false)
+ {
+ var members = shown.Where(belongs).ToArray();
+
+ if (onlyWhenOccupied && members.Length == 0)
{
- var members = shown.Where(belongs).ToArray();
+ return;
+ }
- if (onlyWhenOccupied && members.Length == 0)
- {
- return;
- }
+ var expanded = !collapsedGroups.Contains(group?.EntityId ?? Guid.Empty);
- var expanded = !collapsedGroups.Contains(groupId ?? Guid.Empty);
+ SidebarRows.Add(new SidebarGroupHeader(
+ group?.EntityId,
+ group?.Label ?? "UNGROUPED",
+ members.Length,
+ expanded)
+ {
+ VaultBadge = group?.VaultBadge ?? string.Empty,
+ });
- SidebarRows.Add(new SidebarGroupHeader(groupId, label, members.Length, expanded));
+ if (!expanded)
+ {
+ return;
+ }
- if (!expanded)
- {
- return;
- }
-
- foreach (var member in members)
- {
- SidebarRows.Add(member);
- }
+ foreach (var member in members)
+ {
+ SidebarRows.Add(member);
}
}
@@ -3516,8 +3839,16 @@ internal sealed partial class VaultViewModel(
/// host would be a save the user never asked for, and one they would then be unable to cancel.
///
///
- /// A group id that is not in this vault is not refused — it is treated as no group at all, which is what
- /// the list already does with a dangling reference. See .
+ /// A group id that is in no readable vault is not refused — it is treated as no group at all, which is
+ /// what the list already does with a dangling reference. See .
+ ///
+ ///
+ /// A group in a different vault to the host is refused, and said so. The cards are every readable
+ /// vault's since a group became a thing that can be shared, so this gesture can now be aimed across a
+ /// boundary that a save cannot cross: the host would keep an id only the other vault's holders can
+ /// resolve, and everybody in this one would see it filed under nothing. Refusing beats the two
+ /// alternatives — filing it anyway is the quiet wrong, and treating it as "no group" would unfile a host
+ /// somebody was plainly trying to file.
///
///
/// No cancellation token, for the reason has none: a command generated over a
@@ -3535,33 +3866,24 @@ internal sealed partial class VaultViewModel(
return;
}
- if (row.IsReadOnly)
- {
- // The same refusal editing makes, and for the same reason: re-encoding an item a newer client
- // wrote would drop the fields this build has no concept of.
- Status = "This host was written by a newer version of DodoSSH. Update before filing it.";
- return;
- }
-
- if (IsEditing)
- {
- Status = "Finish or cancel the host you are editing first.";
- return;
- }
-
- Guid? target = request.GroupId is { } wanted && Groups.Any(group => group.EntityId == wanted)
- ? wanted
+ var card = request.GroupId is { } wanted
+ ? Groups.FirstOrDefault(group => group.EntityId == wanted)
: null;
+ if (RefusesTheDrop(row, card))
+ {
+ return;
+ }
+
+ Guid? target = card?.EntityId;
+
if (row.Host.GroupId == target)
{
return;
}
var moved = row.Host with { GroupId = target };
- var name = target is null
- ? "no group"
- : Groups.First(group => group.EntityId == target).Label;
+ var name = card?.Label ?? "no group";
await RunAsync(
$"Filing {row.Label} under {name}…",
@@ -3587,6 +3909,40 @@ internal sealed partial class VaultViewModel(
await AutoSyncAsync(CancellationToken.None).ConfigureAwait(true);
}
+ /// Whether a drop has to be turned down, saying why on the status line when it does.
+ /// The host that was dragged.
+ /// The group card it was dropped on, or null for the drop that unfiles a host.
+ ///
+ /// Three refusals rather than one, and separated from the write so that the reason reaches the status
+ /// line before anything is encrypted. Every one of them is a thing the layer below would either refuse
+ /// or, worse, accept: a newer client's item re-encoded loses fields, a write under an open editor is a
+ /// save nobody asked for, and a group in another vault is an id half the readers cannot resolve.
+ ///
+ private bool RefusesTheDrop(HostRowViewModel row, HostGroupRowViewModel? card)
+ {
+ if (row.IsReadOnly)
+ {
+ Status = "This host was written by a newer version of DodoSSH. Update before filing it.";
+ return true;
+ }
+
+ if (IsEditing)
+ {
+ Status = "Finish or cancel the host you are editing first.";
+ return true;
+ }
+
+ if (card is not null && card.VaultId != row.VaultId)
+ {
+ Status =
+ $"'{card.Label}' is in {card.VaultName} and '{row.Label}' is in {row.VaultName}. "
+ + "A host can only be filed under a group in its own vault.";
+ return true;
+ }
+
+ return false;
+ }
+
/// Whether one host belongs on the grid at the level it is currently showing.
///
///
@@ -4030,10 +4386,16 @@ internal sealed partial class VaultViewModel(
///
/// This is the whole of how a shared vault arrives. Sharing is two acts on two machines: the
/// person sharing wraps the vault key to the recipient, and the recipient's own client has to notice.
- /// The recipient is handed nothing — there is no push channel — so without this the vault list stayed
- /// exactly as it was cached at sign-in, and a vault shared with somebody appeared on their machine only
- /// if they happened to sign in through the browser again. Everything else was already right, which is
- /// why it looked like sharing was broken rather than like a list that was never re-read.
+ /// Without this the vault list stayed exactly as it was cached at sign-in, and a vault shared with
+ /// somebody appeared on their machine only if they happened to sign in through the browser again.
+ /// Everything else was already right, which is why it looked like sharing was broken rather than like a
+ /// list that was never re-read.
+ ///
+ ///
+ /// The server now says when this is worth doing — a vaults.changed notice wakes the pass, so the
+ /// vault turns up as it is shared rather than within the minute — but that only decides when.
+ /// This call is still what discovers the vault, on the notice and on every timed pass alike, because a
+ /// client with no socket has to arrive at the same place. See ADR 0012.
///
///
/// A failure is left to the caller, which treats it as the pass failing: the call is to the same server
@@ -4080,6 +4442,7 @@ internal sealed partial class VaultViewModel(
private async Task RunAutoSyncLoopAsync(CancellationToken cancellationToken)
{
using var timer = new PeriodicTimer(AutoSyncInterval);
+ var waits = new AutoSyncWaits();
try
{
@@ -4094,7 +4457,7 @@ internal sealed partial class VaultViewModel(
// user is doing something.
await SyncOnOpenAsync(cancellationToken).ConfigureAwait(true);
- while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(true))
+ while (await WaitForWorkAsync(timer, waits, cancellationToken).ConfigureAwait(true))
{
await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
}
@@ -4105,6 +4468,98 @@ internal sealed partial class VaultViewModel(
}
}
+ ///
+ /// Waits for the timer to come round, or for the server to say there is something to fetch.
+ ///
+ /// Whether to run a pass. False means the loop is over.
+ ///
+ ///
+ /// The timer is unchanged and is still what guarantees a pass. The socket only makes one
+ /// early, which is why nothing here treats its absence as a problem: no connection, a
+ /// server without the feature, a network that eats WebSockets, or a notice dropped under
+ /// backpressure all leave a loop that behaves exactly as it did before this existed. See ADR 0012.
+ ///
+ ///
+ /// Both waits are held across iterations, and that is load-bearing rather than an
+ /// optimisation. permits only one outstanding
+ /// WaitForNextTickAsync and throws on a second, and an abandoned channel read stays
+ /// registered and consumes the next notice written — which would silently lose exactly the wake-up
+ /// this is for. Whichever wait did not win is kept and awaited again.
+ ///
+ ///
+ private async Task WaitForWorkAsync(
+ PeriodicTimer timer,
+ AutoSyncWaits waits,
+ CancellationToken cancellationToken)
+ {
+ // Re-read every time, because signing out and back in replaces the connection — and with it
+ // the stream. A read still pending against the old one is left to be cancelled with it.
+ var stream = connection()?.Events;
+
+ if (!ReferenceEquals(stream, waits.Watching))
+ {
+ waits.Watching = stream;
+ waits.Notice = null;
+ }
+
+ waits.Tick ??= timer.WaitForNextTickAsync(cancellationToken).AsTask();
+ waits.Notice ??= stream?.ReadAsync(cancellationToken).AsTask();
+
+ if (waits.Notice is null)
+ {
+ var only = waits.Tick;
+ waits.Tick = null;
+
+ return await only.ConfigureAwait(true);
+ }
+
+ var first = await Task.WhenAny(waits.Tick, waits.Notice).ConfigureAwait(true);
+
+ if (ReferenceEquals(first, waits.Tick))
+ {
+ var ticked = waits.Tick;
+ waits.Tick = null;
+
+ return await ticked.ConfigureAwait(true);
+ }
+
+ // Observed so a faulted read does not go unhandled, and so a stream that has been disposed
+ // ends this wait rather than being asked again.
+ await waits.Notice.ConfigureAwait(true);
+ waits.Notice = null;
+
+ // A burst — one person's save is two items, and a colleague tidying a folder is a dozen —
+ // deserves one pass rather than one each.
+ await Task.Delay(NoticeDebounce, cancellationToken).ConfigureAwait(true);
+
+ while (stream!.TryRead(out _))
+ {
+ // Swallowed on purpose. Every notice means the same thing, which is what the pass about to
+ // run already does; what they say about *which* vault is not read, because a pass syncs
+ // every vault this session can reach anyway.
+ }
+
+ return true;
+ }
+
+ /// The two waits the background loop keeps alive between passes.
+ ///
+ /// A class rather than three locals because has to hand them back
+ /// changed, and a method that took three ref parameters could not be async. See that
+ /// method for why abandoning either of them is a defect rather than a tidiness question.
+ ///
+ private sealed class AutoSyncWaits
+ {
+ /// The pending timer tick, or null when the last one has been consumed.
+ internal Task? Tick { get; set; }
+
+ /// The pending read from the server's push channel.
+ internal Task? Notice { get; set; }
+
+ /// The stream was taken from, to notice a reconnection.
+ internal IVaultEventStream? Watching { get; set; }
+ }
+
/// Shows one kind of item, if nothing is being edited.
///
/// Takes the section rather than there being one command per kind, so a third kind is an enum member and
@@ -4421,7 +4876,14 @@ internal sealed partial class VaultViewModel(
/// Duplicate names are allowed. Two groups called "staging" are confusing and they are not
/// wrong — hosts point at ids, so the two are genuinely separate folders — and refusing the
/// second one would mean a name somebody chose on another machine could block one they choose here, at
- /// the next sync, with the rename already saved.
+ /// the next sync, with the rename already saved. Two vaults holding one each is not even confusing: the
+ /// card and the heading both say which vault, and they are as separate as two vaults can make them.
+ ///
+ ///
+ /// Writes to , which is the group's own vault on a rename and whatever
+ /// the picker said when the form opened on a create. Never the active vault, which is what it was while
+ /// the list held one vault's groups: a rename typed into a colleague's group would have created a second
+ /// group of that name in the personal vault and left theirs untouched.
///
///
[RelayCommand]
@@ -4454,13 +4916,13 @@ internal sealed partial class VaultViewModel(
if (renaming is { } entityId)
{
await session.HostGroups
- .UpdateAsync(session.ActiveVaultId, entityId, group, cancellationToken)
+ .UpdateAsync(GroupEditorVaultId, entityId, group, cancellationToken)
.ConfigureAwait(true);
}
else
{
await session.HostGroups
- .CreateAsync(session.ActiveVaultId, group, cancellationToken)
+ .CreateAsync(GroupEditorVaultId, group, cancellationToken)
.ConfigureAwait(true);
}
@@ -4475,11 +4937,22 @@ internal sealed partial class VaultViewModel(
}
/// Loads the group being acted on into the box, so saving renames it.
- /// The selected card, or the open group when no card is selected. See .
+ ///
+ /// The group to edit, or null for whatever the screen is aimed at — the selected card, or the open group
+ /// when no card is selected. See . The desktop's card menu passes nothing and
+ /// means the card that was right-clicked, which opening the menu has already selected; the phone has no
+ /// card to select and passes the group its heading names.
+ ///
+ ///
+ /// Taking it as an argument is what keeps the phone from having to select a group in order to edit one.
+ /// A selection is shared with the host grid now — see — so a command
+ /// reachable only through would deselect the machine somebody was about to
+ /// connect to, on a screen that draws no group cards at all.
+ ///
[RelayCommand]
- private void EditGroup()
+ private void EditGroup(HostGroupRowViewModel? group)
{
- if (GroupTarget is not { } row)
+ if ((group ?? GroupTarget) is not { } row)
{
return;
}
@@ -4491,10 +4964,20 @@ internal sealed partial class VaultViewModel(
}
EditingGroupId = row.EntityId;
+
+ // The group's own vault, and no save moves it — the same rule an existing host's follows, and the
+ // same reason: the two are encrypted under different keys, so saving anywhere else would leave a
+ // copy behind rather than move anything. The picker is not drawn for an existing group at all, and
+ // the move that does work is MoveGroup, from the card's own menu.
+ editingGroupVaultId = row.VaultId;
+ editingGroupVaultName = row.HasVaultBadge ? row.VaultName : string.Empty;
+
GroupEditorLabel = row.Label;
GroupEditorDefaultPort = row.Group.DefaultPort;
GroupEditorDefaultUsername = row.Group.DefaultUsername ?? string.Empty;
+ // Before the parent picker, because that picker is one vault's and this is which one.
+ BuildGroupEditorVaultChoices(row.VaultId);
BuildGroupParentChoices(row.EntityId, row.Group.ParentId);
BuildGroupAuthenticationChoices(row.Group.DefaultSshKeyId, row.Group.DefaultCredentialId);
@@ -4525,6 +5008,12 @@ internal sealed partial class VaultViewModel(
/// deleted by a sync between the list being drawn and the button being pressed — is ignored rather than
/// opening an editor on nothing.
///
+ ///
+ /// The row is handed to rather than selected first, which it used to be. A group
+ /// selection now clears the host selection — the two grids share one mark — and the phone draws no group
+ /// cards, so selecting one here would have taken the highlight off the machine in the list with nothing
+ /// on screen to say where it had gone.
+ ///
///
[RelayCommand]
private void EditGroupFromHeading(SidebarGroupHeader? header)
@@ -4535,8 +5024,7 @@ internal sealed partial class VaultViewModel(
return;
}
- SelectedGroup = row;
- EditGroupCommand.Execute(null);
+ EditGroupCommand.Execute(row);
}
/// Starts a new group, inside whichever one the screen is showing.
@@ -4561,6 +5049,14 @@ internal sealed partial class VaultViewModel(
/// as "and the next group goes inside it" would nest one because somebody had highlighted something,
/// while the open group is the screen everybody can see they are on.
///
+ ///
+ /// And in the open group's vault, which is where this differs from a second
+ /// time. A host opens on the standing "new items go to" preference and takes the open group only if
+ /// that group happens to be in the same vault; a group made inside another group is in that group's
+ /// vault by construction, because a parent in a second vault is a level half the readers cannot resolve.
+ /// Defaulting to the preference instead would answer "+ NEW GROUP inside PLATFORM" with a group
+ /// somewhere else and no parent — a form that silently dropped the one thing the button said.
+ ///
///
[RelayCommand]
private void NewGroup()
@@ -4574,6 +5070,17 @@ internal sealed partial class VaultViewModel(
ClearGroupEditor();
+ // The open group's vault, where there is one and this session can write to it. A viewer of a shared
+ // vault gets the standing preference instead — and, with it, no parent, because the group they were
+ // looking inside belongs to a vault they cannot add to.
+ if (GroupFilter is { } open
+ && GroupEditorVaultChoices.FirstOrDefault(choice => choice.VaultId == open.VaultId) is { } vault)
+ {
+ // Assigned rather than written to the field, so the parent picker is refilled for it: the
+ // handler below is what keeps the two in step, here and when the user moves the picker by hand.
+ GroupEditorSelectedVault = vault;
+ }
+
// Falls back to no parent, which is both what the picker's first entry says and what the phone always
// gets: it has no group cards and no way to go inside one, so nothing there is ever open.
GroupEditorSelectedParent =
@@ -4624,21 +5131,31 @@ internal sealed partial class VaultViewModel(
/// terminates on a cycle. Walking down would need a child index this view model does not keep, and
/// building one that has to survive a cycle is the same problem twice.
///
+ ///
+ /// One vault's candidates, and it is the vault this group is going into rather than the one it is
+ /// on screen beside. The list this picker used to be built from held one vault's groups, so the
+ /// restriction came free; it spans every readable vault now, and offering all of them would let somebody
+ /// file a shared group under a personal one — a parent nobody else can resolve, whose port and username
+ /// would then be lent to their hosts and to nobody else's. Which is the same failure the host editor's
+ /// group picker was fixed for, one level up.
+ ///
///
private void BuildGroupParentChoices(Guid groupId, Guid? parentId)
{
GroupEditorParentChoices.Clear();
GroupEditorParentChoices.Add(GroupChoice.None);
- foreach (var candidate in groupItems.Where(item => item.EntityId != groupId))
+ foreach (var candidate in groupItems.Where(
+ entry => entry.VaultId == GroupEditorVaultId && entry.Item.EntityId != groupId))
{
var descends = HostInheritance
- .Chain(candidate.EntityId, groupsById)
+ .Chain(candidate.Item.EntityId, groupsById)
.Any(entry => entry.Id == groupId);
if (!descends)
{
- GroupEditorParentChoices.Add(new GroupChoice(candidate.EntityId, candidate.Secret.Label));
+ GroupEditorParentChoices.Add(
+ new GroupChoice(candidate.Item.EntityId, candidate.Item.Secret.Label));
}
}
@@ -4654,6 +5171,54 @@ internal sealed partial class VaultViewModel(
?? GroupChoice.None;
}
+ /// Refills the group editor's vault picker, landing on the vault the editor will write to.
+ ///
+ private void BuildGroupEditorVaultChoices(Guid vaultId)
+ {
+ GroupEditorVaultChoices.Clear();
+
+ foreach (var choice in TargetVaults)
+ {
+ GroupEditorVaultChoices.Add(choice);
+ }
+
+ // Null where the group's vault is one this session cannot write — a shared vault this account is a
+ // viewer of. The picker is not drawn for an existing group anyway, and an empty box is a better
+ // answer than an option that would move the group if it were touched.
+ GroupEditorSelectedVault =
+ GroupEditorVaultChoices.FirstOrDefault(choice => choice.VaultId == vaultId);
+
+ OnPropertyChanged(nameof(ShowsGroupEditorVaultChoice));
+ }
+
+ ///
+ /// Moves a half-typed group into the vault just chosen for it.
+ ///
+ ///
+ /// Only while creating, for the reason gives: a save cannot
+ /// move a group between vaults, so a path that reassigned this on a rename would write a second group
+ /// into the other vault and leave the original standing with the old name. Moving one is
+ /// , which does the re-seal and the tombstone this could not.
+ ///
+ partial void OnGroupEditorSelectedVaultChanged(VaultChoiceViewModel? value)
+ {
+ if (value is null || EditingGroupId is not null || editingGroupVaultId == value.VaultId)
+ {
+ return;
+ }
+
+ editingGroupVaultId = value.VaultId;
+
+ // The parent picker is the vault's, so it has to be rebuilt — and whatever was chosen in it belongs
+ // to the vault just left, so it is dropped rather than carried: a group is one item in one vault,
+ // and there is nothing in the new one it could mean instead. The defaults below it are not touched,
+ // because a key or a credential may legitimately come from another vault, exactly as a host's may.
+ //
+ // Guid.Empty for the group being edited, because the guard above means there is not one: this only
+ // ever runs while creating, and a group that does not exist yet cannot be its own parent.
+ BuildGroupParentChoices(Guid.Empty, parentId: null);
+ }
+
/// Fills the group's binding picker, keeping whatever it currently defaults to selectable.
///
/// without the typed-password entry and without the inherited
@@ -4717,6 +5282,14 @@ internal sealed partial class VaultViewModel(
GroupEditorDefaultPort = null;
GroupEditorDefaultUsername = string.Empty;
+ // Back to the standing preference rather than to whatever the last group edited was in, which is
+ // the same clearing every other field here gets and matters more than any of them: a vault carried
+ // over from a colleague's group is where the next one would silently go.
+ editingGroupVaultId = TargetVaultId;
+ editingGroupVaultName = string.Empty;
+
+ // Before the parent choices, which are that vault's.
+ BuildGroupEditorVaultChoices(GroupEditorVaultId);
BuildGroupParentChoices(Guid.Empty, parentId: null);
BuildGroupAuthenticationChoices(boundKeyId: null, boundCredentialId: null);
}
@@ -4729,14 +5302,30 @@ internal sealed partial class VaultViewModel(
Status = string.Empty;
}
- /// Asks whether the group being acted on should go.
+ /// Asks whether the group being acted on should go, and what should become of its hosts.
///
- /// The count is the whole reason this asks rather than acting. Deleting a group does not delete the hosts
- /// in it and deliberately does not rewrite them either — they keep an id that no longer resolves and turn
- /// up under the ungrouped heading — so what the user needs to know is exactly how many machines are about
- /// to move, and that none of them are going anywhere else.
///
- /// Aims where EDIT does: at the selected card, or at the open group when no card is selected. See
+ /// The hosts are a second question rather than a stated consequence, and that is a reversal. This
+ /// used to say what would happen to them — they stay, and turn up under UNGROUPED — because a group's
+ /// deletion did not touch them at all. That answer was right for one of the two things people delete a
+ /// group for and wrong for the other: a heading being tidied away should leave its machines alone, and a
+ /// project that has been decommissioned is a shelf and everything on it. Nothing here can tell which of
+ /// the two it is looking at, so it is asked. See .
+ ///
+ ///
+ /// The count is still the reason this asks rather than acting, and it now counts twice over: it is the
+ /// number of machines about to be unfiled, or — with the box ticked — the number about to be destroyed.
+ /// A group with nothing under it gets no second question and no tick, because there is nothing for
+ /// either to be about.
+ ///
+ ///
+ /// Refused with a host editor open, which the deletion of a single host is not. The difference is
+ /// that this one writes to hosts: unfiling rewrites every machine under the heading, and doing that
+ /// beneath a half-typed edit of one of them is the save nobody asked for that
+ /// refuses for the same reason.
+ ///
+ ///
+ /// Aims where Edit does: at the selected card, which on the desktop is the one the menu opened on. See
/// .
///
///
@@ -4748,21 +5337,77 @@ internal sealed partial class VaultViewModel(
return;
}
+ // Only where it would write to a host. A heading with nothing under it is deleted with an editor
+ // open, because nothing on that form is about to be rewritten underneath it.
+ if (row.HostCount > 0 && AHostEditorIsInTheWay())
+ {
+ return;
+ }
+
+ // Disarms a move aimed at the same group, on the reasoning MoveHost uses in the other direction: two
+ // panels about one shelf, one of which destroys it, is not something to make anybody read carefully.
+ CancelMoveGroupCommand.Execute(null);
+
PendingDeletion = new DeletionRequest(
DeletionTarget.Group,
row.EntityId,
- $"Delete the group '{row.Label}'?",
+
+ // Named with its vault where there is more than one, because two of them may hold a group of
+ // this name and the question is about exactly one of the two. The badge is already the answer
+ // the card gives; this is the same answer at the moment it decides something.
+ row.HasVaultBadge
+ ? $"Delete the group '{row.Label}' in {row.VaultName}?"
+ : $"Delete the group '{row.Label}'?",
HowFarADeletionGoes("The group"),
row.HostCount switch
{
0 => string.Empty,
- 1 => "1 host is filed under it. The host stays; it moves to UNGROUPED.",
- _ => $"{row.HostCount} hosts are filed under it. They stay; they move to UNGROUPED.",
- });
+ 1 => "1 host is filed under it. Left as it is, the host stays and moves to UNGROUPED.",
+ _ => $"{row.HostCount} hosts are filed under it. Left as it is, they stay and move to "
+ + "UNGROUPED.",
+ })
+ {
+ Choice = row.HostCount switch
+ {
+ 0 => string.Empty,
+ 1 => "Delete the host filed under it as well.",
+ _ => $"Delete the {row.HostCount} hosts filed under it as well.",
+ },
+ };
}
- /// Queues a tombstone for the group that was agreed to.
- private async Task DeleteGroupNowAsync(Guid entityId, CancellationToken cancellationToken)
+ ///
+ /// Queues the tombstone for the group that was agreed to, and settles what pointed at it.
+ ///
+ ///
+ ///
+ /// Nothing is left pointing at the group. That is the change: the hosts filed under it are
+ /// rewritten — unfiled, or deleted where that was asked for — and the groups nested inside it take its
+ /// place in the tree rather than being orphaned into roots. It costs one write per item and it is the
+ /// honest cost of the question above it. The dangling reference the list used to absorb is still handled
+ /// everywhere it is read, because a group deleted on another machine still arrives that way.
+ ///
+ ///
+ /// Everything that points at it is written before the group's own tombstone. A crash in the middle
+ /// then leaves a heading standing over fewer things, which is visible and can simply be deleted again;
+ /// the other order leaves a group gone with its members still naming it, which is exactly the state this
+ /// exists to stop producing. It also matters against a merge: the group's tombstone can lose one, and if
+ /// it does, the unfiling has already been recorded on its own items rather than riding on it.
+ ///
+ ///
+ /// A read-only host is skipped and counted rather than rewritten. Unfiling it would re-encode a
+ /// payload this build cannot fully represent, which is the same refusal editing and moving one already
+ /// make — and the cost of skipping is a dangling id, which is the behaviour every reader here already
+ /// survives. Deleting one is not skipped: a tombstone re-encodes nothing.
+ ///
+ ///
+ /// The group.
+ /// Whether the hosts filed under it were agreed to go too.
+ /// Cancellation token.
+ private async Task DeleteGroupNowAsync(
+ Guid entityId,
+ bool takesTheHosts,
+ CancellationToken cancellationToken)
{
if (Groups.FirstOrDefault(row => row.EntityId == entityId) is not { } row)
{
@@ -4770,12 +5415,29 @@ internal sealed partial class VaultViewModel(
return;
}
+ // Its own vault's, both of them. A host in another vault naming this group is a reference the editor
+ // cannot make and the drop gesture refuses, so the only way to hold one is a hand-edited payload —
+ // and rewriting somebody else's vault because a group in this one went is worse than the dangle.
+ var filed = Hosts
+ .Where(host => host.VaultId == row.VaultId && host.Host.GroupId == entityId)
+ .ToList();
+
+ var nested = Groups
+ .Where(group => group.VaultId == row.VaultId && group.Group.ParentId == entityId)
+ .ToList();
+
await RunAsync(
"Deleting…",
async () =>
{
+ var skipped = await ReleaseWhatPointedAtAsync(row, filed, nested, takesTheHosts, cancellationToken)
+ .ConfigureAwait(true);
+
+ // The row's own vault, which is why the row is re-found above rather than the id being
+ // enough: a tombstone written to the active vault would delete nothing and leave a
+ // colleague's group standing while this machine reported it gone.
await session.HostGroups
- .DeleteAsync(session.ActiveVaultId, row.EntityId, cancellationToken)
+ .DeleteAsync(row.VaultId, row.EntityId, cancellationToken)
.ConfigureAwait(true);
if (EditingGroupId == entityId)
@@ -4785,12 +5447,91 @@ internal sealed partial class VaultViewModel(
}
await ReloadAsync(cancellationToken).ConfigureAwait(true);
- Status = $"Deleted the group '{row.Label}'.";
+
+ Status = $"Deleted the group '{row.Label}'."
+ + WhatBecameOfTheHosts(filed.Count, takesTheHosts, skipped);
}).ConfigureAwait(true);
await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
}
+ ///
+ /// Rewrites everything naming the group about to go, and says how many could not be.
+ ///
+ ///
+ /// Before the tombstone and in this order, which gives the reasons for.
+ ///
+ /// How many hosts were left holding the reference because they could not be rewritten.
+ private async Task ReleaseWhatPointedAtAsync(
+ HostGroupRowViewModel row,
+ IEnumerable filed,
+ IEnumerable nested,
+ bool takesTheHosts,
+ CancellationToken cancellationToken)
+ {
+ var skipped = 0;
+
+ foreach (var host in filed)
+ {
+ if (takesTheHosts)
+ {
+ await session.Hosts
+ .DeleteAsync(host.VaultId, host.EntityId, cancellationToken)
+ .ConfigureAwait(true);
+
+ continue;
+ }
+
+ if (host.IsReadOnly)
+ {
+ skipped++;
+ continue;
+ }
+
+ await session.Hosts
+ .UpdateAsync(
+ host.VaultId,
+ host.EntityId,
+ host.Host with { GroupId = null },
+ cancellationToken)
+ .ConfigureAwait(true);
+ }
+
+ // Promoted to where the group they were under sat, rather than to the top level. A nested group whose
+ // parent goes has not been moved by anybody, and dropping it to a root would rearrange a tree on a
+ // delete that was about one heading.
+ foreach (var child in nested.Where(child => !child.IsReadOnly))
+ {
+ await session.HostGroups
+ .UpdateAsync(
+ child.VaultId,
+ child.EntityId,
+ child.Group with { ParentId = row.Group.ParentId },
+ cancellationToken)
+ .ConfigureAwait(true);
+ }
+
+ return skipped;
+ }
+
+ /// What the group's deletion did to the machines under it, said only when there were any.
+ ///
+ /// The skipped count is named rather than folded into the total, because those hosts are the ones still
+ /// holding the deleted group's id: they show up under UNGROUPED like the rest, so nothing looks wrong,
+ /// and the sentence is the only place anybody is told that updating this client is what finishes the job.
+ ///
+ private static string WhatBecameOfTheHosts(int filed, bool takesTheHosts, int skipped) =>
+ (filed, takesTheHosts, skipped) switch
+ {
+ (0, _, _) => string.Empty,
+ (1, true, _) => " Its host went with it.",
+ (_, true, _) => $" Its {filed} hosts went with it.",
+ (1, false, 0) => " Its host moved to UNGROUPED.",
+ (_, false, 0) => $" Its {filed} hosts moved to UNGROUPED.",
+ _ => $" Its {filed} hosts moved to UNGROUPED, except {skipped} written by a newer version of "
+ + "DodoSSH — those still name the group that has gone. Update to unfile them.",
+ };
+
/// Abandons the editor.
[RelayCommand]
private void CancelEdit()
@@ -4907,6 +5648,532 @@ internal sealed partial class VaultViewModel(
return imported;
}
+ ///
+ /// Opens the panel that asks which vault the selected host should move to.
+ ///
+ ///
+ ///
+ /// A panel rather than a picker in the host editor, and the reason is what a move is underneath: the
+ /// item is re-sealed under another vault's key and the one it came from gets a tombstone — see
+ /// VaultItemRepository.MoveAsync. That is not a field of the host and must not be saved with
+ /// one, or somebody correcting a port would move a machine into a colleague's vault by leaving a
+ /// picker where they found it.
+ ///
+ ///
+ /// Refused for a host written by a newer client, exactly as editing one is: the move re-encodes the
+ /// payload, so a field this build cannot represent would be dropped on the way across.
+ ///
+ ///
+ [RelayCommand]
+ private void MoveHost()
+ {
+ if (SelectedHost is not { } row || AHostEditorIsInTheWay())
+ {
+ return;
+ }
+
+ if (row.IsReadOnly)
+ {
+ Status = "This host was written by a newer version of DodoSSH. Moving it would re-encode it "
+ + "here and lose what this build cannot read. Update first.";
+ return;
+ }
+
+ BuildMoveVaultChoices(row.VaultId);
+
+ if (MoveVaultChoices.Count == 0)
+ {
+ // The one-vault case, and the honest sentence rather than an empty picker. It is also what
+ // somebody in a team whose only other vault is read-only sees.
+ Status = $"There is nowhere to move '{row.Label}' to: this is the only vault you can write to.";
+ return;
+ }
+
+ // Disarms a deletion aimed at the same host. Two questions about one machine, one of which
+ // destroys it, is not a pane anybody should have to read carefully.
+ PendingDeletion = null;
+ movingHostId = row.EntityId;
+ IsMovingHost = true;
+ Status = string.Empty;
+ }
+
+ /// Abandons the move panel.
+ [RelayCommand]
+ private void CancelMoveHost()
+ {
+ IsMovingHost = false;
+ movingHostId = null;
+ MoveVaultChoices.Clear();
+ SelectedMoveVault = null;
+ Status = string.Empty;
+ }
+
+ ///
+ /// Moves the selected host into the chosen vault.
+ ///
+ ///
+ ///
+ /// The group and the tags are left behind, and that is the whole of what makes this honest. Both
+ /// are items of the vault the host is leaving: the group picker in the editor offers one vault's groups
+ /// and the tag chips are drawn from one vault's tags, so a host carrying either across would point at
+ /// something the destination does not contain. On this machine it would still resolve — groups and tags
+ /// are resolved across every readable vault — and for everybody else in the destination it would dangle,
+ /// which means the mover and their colleagues would see two different hosts. Cleared and reported beats
+ /// carried and invisible.
+ ///
+ ///
+ /// The key or password binding is kept, and the difference is not inconsistency. Those genuinely
+ /// resolve across vaults — one key on twenty hosts in three vaults is the arrangement they exist for —
+ /// so clearing them would take a working host and make it one that cannot connect. What it can do is say
+ /// when the binding is now in a different vault from the host, because that is exactly what the other
+ /// members of the destination will not be able to resolve.
+ ///
+ ///
+ /// The row is re-selected by its new id afterwards. A move that left the pane on a host that no longer
+ /// exists would read as the machine having been deleted.
+ ///
+ ///
+ [RelayCommand]
+ private async Task ConfirmMoveHostAsync(CancellationToken cancellationToken)
+ {
+ if (SelectedHost is not { } row || SelectedMoveVault is not { } target)
+ {
+ return;
+ }
+
+ var name = target.Name;
+ var dropped = WhatWasLeftBehind(row.Host);
+ var stranded = BindingOutside(row.Host, target.VaultId);
+
+ var moved = row.Host with { GroupId = null, TagIds = TagSet.Empty };
+
+ IsMovingHost = false;
+ movingHostId = null;
+ MoveVaultChoices.Clear();
+ SelectedMoveVault = null;
+
+ await RunAsync(
+ "Moving…",
+ async () =>
+ {
+ var entityId = await session.Hosts
+ .MoveAsync(row.VaultId, target.VaultId, row.EntityId, moved, cancellationToken)
+ .ConfigureAwait(true);
+
+ await ReloadAsync(cancellationToken).ConfigureAwait(true);
+
+ SelectedHost = Hosts.FirstOrDefault(host => host.EntityId == entityId);
+
+ Status = $"Moved '{row.Label}' to {name}.{dropped}{stranded}";
+ }).ConfigureAwait(true);
+
+ // As a save and a deletion do. A move is two writes in two vaults, and a machine that syncs one of
+ // them and not the other shows the host twice or not at all until the next pass.
+ await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
+ }
+
+ /// What the move left behind, said only when it left something.
+ private static string WhatWasLeftBehind(HostSecret host) =>
+ (host.GroupId is not null, host.TagIds.Count > 0) switch
+ {
+ (true, true) => " Its group and tags were left behind — both belong to the vault it came from.",
+ (true, false) => " Its group was left behind — a group belongs to the vault it is in.",
+ (false, true) => " Its tags were left behind — a tag belongs to the vault it is in.",
+ _ => string.Empty,
+ };
+
+ ///
+ /// The warning about a key or password that is not in the vault the host has moved to.
+ ///
+ ///
+ /// Named rather than counted, because which one it is decides what to do about it — and the answer is
+ /// usually to put a copy of that key in the destination vault, which needs to know which key.
+ ///
+ private string BindingOutside(HostSecret host, Guid vaultId)
+ {
+ if (host.SshKeyId is { } keyId
+ && Keys.FirstOrDefault(row => row.EntityId == keyId) is { } key
+ && key.VaultId != vaultId)
+ {
+ return $" It still authenticates with the key '{key.Label}', which is in another vault — "
+ + "everybody else in this one will find that binding unresolvable.";
+ }
+
+ if (host.CredentialId is { } credentialId
+ && Credentials.FirstOrDefault(row => row.EntityId == credentialId) is { } credential
+ && credential.VaultId != vaultId)
+ {
+ return $" It still authenticates with the password '{credential.Label}', which is in another "
+ + "vault — everybody else in this one will find that binding unresolvable.";
+ }
+
+ return string.Empty;
+ }
+
+ /// Fills the move panel's picker with every vault this session can write to but that one.
+ private void BuildMoveVaultChoices(Guid vaultId)
+ {
+ MoveVaultChoices.Clear();
+
+ foreach (var choice in WritableVaultsBesides(vaultId))
+ {
+ MoveVaultChoices.Add(choice);
+ }
+
+ SelectedMoveVault = MoveVaultChoices.FirstOrDefault();
+ }
+
+ /// Every vault this session can write to except one, in the order a picker should offer them.
+ ///
+ /// Shared by the host's picker and the group's rather than written twice. The order is the one every
+ /// vault picker in this application uses: your own first, then the shared ones by name — a list that
+ /// re-sorted itself per control would make "the second entry" mean something different on each.
+ ///
+ private IEnumerable WritableVaultsBesides(Guid vaultId) =>
+ session.ReadableVaults
+ .Where(vault => vault.CanWrite && vault.VaultId != vaultId)
+ .OrderByDescending(vault => vault.IsPersonal)
+ .ThenBy(vault => vault.Name, StringComparer.CurrentCulture)
+ .Select(vault => new VaultChoiceViewModel(vault.VaultId, vault.Name, vault.IsPersonal));
+
+ ///
+ /// Opens the panel that asks which vault the group — and everything under it — should move to.
+ ///
+ ///
+ ///
+ /// The host's panel, one level up, and the reason it exists at all is that the host's did not go far
+ /// enough. Moving twenty machines into a shared vault one at a time meant twenty round trips through a
+ /// menu, and each one arrived stripped of the group it had been filed under, so the shelf had to be
+ /// rebuilt by hand on the other side. Moving the shelf is the operation people were actually attempting.
+ ///
+ ///
+ /// Refused for a group written by a newer client, as editing one is, and refused with a host editor open,
+ /// as is: this rewrites hosts.
+ ///
+ ///
+ [RelayCommand]
+ private void MoveGroup()
+ {
+ if (GroupTarget is not { } row || AHostEditorIsInTheWay() || AGroupEditorIsInTheWay())
+ {
+ return;
+ }
+
+ if (row.IsReadOnly)
+ {
+ Status = "This group was written by a newer version of DodoSSH. Moving it would re-encode it "
+ + "here and lose what this build cannot read. Update first.";
+ return;
+ }
+
+ BuildMoveGroupVaultChoices(row.VaultId);
+
+ if (MoveGroupVaultChoices.Count == 0)
+ {
+ Status = $"There is nowhere to move '{row.Label}' to: this is the only vault you can write to.";
+ return;
+ }
+
+ // As MoveHost disarms a deletion aimed at the same host.
+ PendingDeletion = null;
+ movingGroupId = row.EntityId;
+ IsMovingGroup = true;
+ Status = string.Empty;
+ }
+
+ /// Abandons the group's move panel.
+ [RelayCommand]
+ private void CancelMoveGroup()
+ {
+ if (!IsMovingGroup)
+ {
+ return;
+ }
+
+ IsMovingGroup = false;
+ movingGroupId = null;
+ MoveGroupVaultChoices.Clear();
+ SelectedMoveGroupVault = null;
+ Status = string.Empty;
+ }
+
+ ///
+ /// Moves the group, everything nested inside it and every host filed under any of them.
+ ///
+ ///
+ ///
+ /// The whole subtree goes, and taking less than that was never coherent. A group's children are
+ /// items of the vault it is leaving: move the parent alone and they are left naming a tombstone, so they
+ /// surface as roots in the vault the user has just emptied — half a shelf here and half there, from one
+ /// gesture that said "move this". The hosts are the same argument and are the half the user asked about.
+ ///
+ ///
+ /// The groups go first, top down, and the hosts last. Each item is re-sealed under the
+ /// destination's key and takes a new id — see VaultItemRepository.MoveAsync — so nothing that
+ /// points at a group can be written until that group has landed and its new id is known. Top down for
+ /// the same reason one level up: a child's parent must already be over there. What an interruption
+ /// leaves is therefore hosts still in the vault they started in, under UNGROUPED, which is visible and
+ /// re-movable; the reverse order would leave hosts in the destination filed under nothing.
+ ///
+ ///
+ /// The parent is left behind and the tags are dropped, and both are the same rule the host's move
+ /// follows: a parent group and a tag are items of the vault being left, so a reference carried across
+ /// would resolve on this machine — groups and tags resolve over every readable vault — and dangle for
+ /// everybody else in the destination. The moved group becomes a root, which is what the trail will show,
+ /// and it is said in the sentence afterwards rather than discovered.
+ ///
+ ///
+ /// Keys and passwords are kept, on the host and on the group's own defaults, because those do
+ /// genuinely resolve across vaults — one key on twenty hosts in three vaults is the arrangement they
+ /// exist for. What is reported is a binding now outside the destination, since that is precisely what
+ /// the other holders of it will not be able to resolve.
+ ///
+ ///
+ [RelayCommand]
+ private async Task ConfirmMoveGroupAsync(CancellationToken cancellationToken)
+ {
+ if (GroupTarget is not { } row
+ || movingGroupId != row.EntityId
+ || SelectedMoveGroupVault is not { } target)
+ {
+ return;
+ }
+
+ var subtree = SubtreeOf(row);
+ var moving = subtree.Select(group => group.EntityId).ToHashSet();
+
+ var filed = Hosts
+ .Where(host => host.VaultId == row.VaultId && host.Host.GroupId is { } id && moving.Contains(id))
+ .ToList();
+
+ // Asked once, over everything that is about to be re-encoded, and refused as a whole rather than
+ // half-done: a move that skipped the items it could not represent would file some of the shelf in one
+ // vault and leave the rest in the other, which is the state this operation exists to prevent.
+ if (subtree.Any(group => group.IsReadOnly) || filed.Any(host => host.IsReadOnly))
+ {
+ Status = "Something under this group was written by a newer version of DodoSSH. Moving it would "
+ + "re-encode it here and lose what this build cannot read. Update first.";
+ return;
+ }
+
+ var name = target.Name;
+ var stranded = BindingsOutside(subtree, filed, target.VaultId);
+ var uprooted = row.Group.ParentId is not null;
+ var tagged = filed.Count(host => host.Host.TagIds.Count > 0);
+
+ CancelMoveGroupCommand.Execute(null);
+
+ await RunAsync(
+ "Moving…",
+ async () =>
+ {
+ var landed = await ReSealTheSubtreeAsync(subtree, filed, target.VaultId, cancellationToken)
+ .ConfigureAwait(true);
+
+ await ReloadAsync(cancellationToken).ConfigureAwait(true);
+
+ // By its new id, as a moved host's pane is: leaving the buttons aimed at a card that no
+ // longer exists would read as the shelf having been deleted rather than moved.
+ SelectedGroup = VisibleGroups.FirstOrDefault(card => card.EntityId == landed);
+
+ Status = $"Moved '{row.Label}' to {name}.{WhatCameAlong(subtree.Count, filed.Count)}"
+ + $"{WhatStayedBehind(uprooted, tagged)}{stranded}";
+ }).ConfigureAwait(true);
+
+ await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
+ }
+
+ ///
+ /// Re-seals a group, its nested groups and their hosts under another vault's key.
+ ///
+ ///
+ /// The order and what it costs an interruption are 's to explain. What
+ /// lives here is the id map every write after the first depends on: each item lands with an id of the
+ /// destination's making, so a parent's is looked up rather than reused, and a host's group is the entry
+ /// its old group left behind.
+ ///
+ /// The group and its nested groups, each after its parent.
+ /// The hosts under any of them.
+ /// The vault they are all going to.
+ /// Cancellation token.
+ /// The id the group at the root of it has in its new vault.
+ private async Task ReSealTheSubtreeAsync(
+ List subtree,
+ IEnumerable filed,
+ Guid vaultId,
+ CancellationToken cancellationToken)
+ {
+ var root = subtree[0].EntityId;
+ var remapped = new Dictionary();
+
+ foreach (var group in subtree)
+ {
+ // Null for the root, whose parent is staying behind in the vault it came from; every other group
+ // in the list was discovered by its own parent, so that parent has already landed.
+ var parent = group.EntityId == root
+ ? (Guid?)null
+ : remapped[group.Group.ParentId!.Value];
+
+ remapped[group.EntityId] = await session.HostGroups
+ .MoveAsync(
+ group.VaultId,
+ vaultId,
+ group.EntityId,
+ group.Group with { ParentId = parent },
+ cancellationToken)
+ .ConfigureAwait(true);
+ }
+
+ foreach (var host in filed)
+ {
+ await session.Hosts
+ .MoveAsync(
+ host.VaultId,
+ vaultId,
+ host.EntityId,
+ host.Host with
+ {
+ GroupId = remapped[host.Host.GroupId!.Value],
+ TagIds = TagSet.Empty,
+ },
+ cancellationToken)
+ .ConfigureAwait(true);
+ }
+
+ return remapped[root];
+ }
+
+ ///
+ /// The group and every group nested under it, each one after the group it hangs from.
+ ///
+ ///
+ ///
+ /// A breadth-first walk from the root, and the order is the whole reason it is one: every group but the
+ /// first is discovered by its parent, so a caller writing the list in order always has the
+ /// parent's new id in hand before it needs it.
+ ///
+ ///
+ /// Its own vault's only, because a child in another vault is a level half the readers cannot resolve and
+ /// the editor refuses to make one.
+ ///
+ ///
+ /// Cycle-safe, and it has to be. A group already found is not walked again and not added twice —
+ /// the same visited set every walk over this tree carries, for the reason
+ /// gives: two offline clients can each re-parent one group under
+ /// the other, and the pair that results was never shown to an editor. Without the set, a group that is
+ /// its own parent would be appended to this list for as long as there was memory to append to.
+ ///
+ ///
+ private List SubtreeOf(HostGroupRowViewModel root)
+ {
+ var ordered = new List { root };
+ var found = new HashSet { root.EntityId };
+
+ for (var index = 0; index < ordered.Count; index++)
+ {
+ var parent = ordered[index].EntityId;
+
+ foreach (var child in Groups.Where(
+ group => group.VaultId == root.VaultId && group.Group.ParentId == parent))
+ {
+ if (found.Add(child.EntityId))
+ {
+ ordered.Add(child);
+ }
+ }
+ }
+
+ return ordered;
+ }
+
+ /// What the move brought with it, said as the counts the user can check against the cards.
+ private static string WhatCameAlong(int groups, int hosts)
+ {
+ var nested = groups switch
+ {
+ 1 => string.Empty,
+ 2 => " with the group inside it",
+ _ => $" with the {groups - 1} groups inside it",
+ };
+
+ return hosts switch
+ {
+ 0 when groups == 1 => string.Empty,
+ 0 => $" It went{nested}, and no hosts were filed under any of them.",
+ 1 => $" Its host came too{nested}.",
+ _ => $" Its {hosts} hosts came too{nested}.",
+ };
+ }
+
+ /// The two things a group cannot take across, said only where it had one.
+ private static string WhatStayedBehind(bool uprooted, int tagged) =>
+ (uprooted, tagged > 0) switch
+ {
+ (true, true) => " The group it was nested under stayed behind and the hosts' tags were dropped —"
+ + " both belong to the vault it came from, so it now sits at the top level.",
+ (true, false) => " The group it was nested under stayed behind — a parent belongs to the vault it"
+ + " is in — so it now sits at the top level.",
+ (false, true) => " The hosts' tags were left behind — a tag belongs to the vault it is in.",
+ _ => string.Empty,
+ };
+
+ ///
+ /// The warning about keys or passwords that are not in the vault the group has moved to.
+ ///
+ ///
+ /// Counted and named to one, where names the only one there can be. A shelf
+ /// of twenty machines may strand five different keys, and twenty sentences is not a status line — but a
+ /// bare number is not actionable either, so the first is named and the rest are counted. Both the hosts'
+ /// own bindings and the groups' defaults are asked, because a group that lends a key is the one case
+ /// where a machine can be unable to connect without naming anything itself.
+ ///
+ private string BindingsOutside(
+ IEnumerable groups,
+ IEnumerable hosts,
+ Guid vaultId)
+ {
+ var stranded = groups
+ .SelectMany(group => new[] { group.Group.DefaultSshKeyId, group.Group.DefaultCredentialId })
+ .Concat(hosts.SelectMany(host => new[] { host.Host.SshKeyId, host.Host.CredentialId }))
+ .OfType()
+ .Distinct()
+ .Select(LabelOfBindingOutside)
+ .OfType()
+ .ToList();
+
+ return stranded.Count switch
+ {
+ 0 => string.Empty,
+ 1 => $" It still authenticates with '{stranded[0]}', which is in another vault — everybody else "
+ + "in this one will find that binding unresolvable.",
+ _ => $" It still authenticates with '{stranded[0]}' and {stranded.Count - 1} other key(s) or "
+ + "password(s) in other vaults — everybody else in this one will find those bindings "
+ + "unresolvable.",
+ };
+
+ string? LabelOfBindingOutside(Guid entityId) =>
+ (Keys.FirstOrDefault(key => key.EntityId == entityId) is { } key && key.VaultId != vaultId
+ ? key.Label
+ : null)
+ ?? (Credentials.FirstOrDefault(row => row.EntityId == entityId) is { } credential
+ && credential.VaultId != vaultId
+ ? credential.Label
+ : null);
+ }
+
+ /// Fills the group move panel's picker with every vault this session can write to but that one.
+ private void BuildMoveGroupVaultChoices(Guid vaultId)
+ {
+ MoveGroupVaultChoices.Clear();
+
+ foreach (var choice in WritableVaultsBesides(vaultId))
+ {
+ MoveGroupVaultChoices.Add(choice);
+ }
+
+ SelectedMoveGroupVault = MoveGroupVaultChoices.FirstOrDefault();
+ }
+
/// Asks whether the selected host should go.
///
/// A terminal already open on the host is disclosed rather than prevented, because deleting a host does
@@ -5752,6 +7019,10 @@ internal sealed partial class VaultViewModel(
return;
}
+ // Read before the disarming below, which resets it. The answer belongs to the question that was on
+ // screen, and taking it afterwards would read whatever the next question starts from.
+ var takesTheHosts = DeletionTakesTheHostsToo;
+
PendingDeletion = null;
switch (request.Target)
@@ -5769,7 +7040,8 @@ internal sealed partial class VaultViewModel(
break;
case DeletionTarget.Group:
- await DeleteGroupNowAsync(request.EntityId, cancellationToken).ConfigureAwait(true);
+ await DeleteGroupNowAsync(request.EntityId, takesTheHosts, cancellationToken)
+ .ConfigureAwait(true);
break;
case DeletionTarget.ObjectStore:
@@ -7039,10 +8311,10 @@ internal sealed partial class VaultViewModel(
/// Moves a half-typed host into the vault just chosen for it.
///
///
- /// Only while creating. An existing host's vault is fixed, and this guard is what makes that true
- /// rather than the view merely not drawing the control: an item cannot be moved between vaults, so a
- /// path that reassigned this on an edit would write the host into a second vault and leave the
- /// original behind.
+ /// Only while creating, and this guard is what makes that true rather than the view merely not drawing
+ /// the control. An existing host can change vaults — see — but not this
+ /// way and not as part of a save: reassigning it here on an edit would write the host into a second
+ /// vault and leave the original behind, which is a fork rather than a move.
///
partial void OnEditorSelectedVaultChanged(VaultChoiceViewModel? value)
{
@@ -7402,6 +8674,16 @@ internal sealed partial class VaultViewModel(
partial void OnSelectedHostChanged(HostRowViewModel? value)
{
+ // One selection, across both grids. The two lists are drawn one above the other and they are marked
+ // the same way, so two lit cards read as two things chosen — and the buttons underneath them are two
+ // pairs, only one of which would act. Losing a selection leaves the other alone: a null here is what
+ // a filter matching nothing writes, and taking the mark off a group card because a search box
+ // emptied the grid beneath it would be this rule firing at something that is not a choice.
+ if (value is not null)
+ {
+ SelectedGroup = null;
+ }
+
OnPropertyChanged(nameof(SelectedHostAsksForAPassword));
OnPropertyChanged(nameof(SelectedHostAuthenticationNote));
OnPropertyChanged(nameof(ShowsConnectBar));
@@ -7427,6 +8709,7 @@ internal sealed partial class VaultViewModel(
OnPropertyChanged(nameof(IsDrawerOpen));
OnPropertyChanged(nameof(IsShowingHostDetail));
OnPropertyChanged(nameof(ShowsHostPaneActions));
+ OnPropertyChanged(nameof(CanMoveSelectedHost));
// Kept in step so that selecting a host in code — a reload restoring one, the palette connecting to
// one — lights the right row. Assigning the same value again is a no-op, so the two do not chase each
@@ -7434,6 +8717,17 @@ internal sealed partial class VaultViewModel(
SelectedSidebarRow = value;
DisarmIfAimedElsewhere(DeletionTarget.Host, value?.EntityId);
+
+ // The move panel goes with the selection, as the deletion question does — and by entity id for the
+ // same reason DisarmIfAimedElsewhere compares them: a background pass replaces every row object in
+ // the list, so a panel closed on row identity would fold up once a minute under somebody who was
+ // still choosing a vault in it. A click onto a different host is the case that needs handling, and
+ // it is cleared rather than re-aimed: which vault to move to is a choice about the host it was
+ // asked for.
+ if (IsMovingHost && movingHostId != value?.EntityId)
+ {
+ CancelMoveHostCommand.Execute(null);
+ }
}
///
@@ -7468,12 +8762,22 @@ internal sealed partial class VaultViewModel(
}
}
+ ///
+ /// The other half of the shared selection; see . Clearing the host
+ /// takes the drawer with it, and that is the point rather than a side effect: a pane about one machine
+ /// cannot go on standing beside a marked group, since nothing on it would be about what is selected.
+ ///
partial void OnSelectedGroupChanged(HostGroupRowViewModel? value)
{
+ if (value is not null)
+ {
+ SelectedHost = null;
+ }
+
DisarmIfAimedElsewhere(DeletionTarget.Group, GroupTarget?.EntityId);
+ CloseTheGroupMovePanelIfAimedElsewhere();
OnPropertyChanged(nameof(GroupTarget));
- OnPropertyChanged(nameof(ShowsGroupActions));
}
///
@@ -7492,22 +8796,41 @@ internal sealed partial class VaultViewModel(
partial void OnGroupFilterChanged(HostGroupRowViewModel? value)
{
DisarmIfAimedElsewhere(DeletionTarget.Group, GroupTarget?.EntityId);
+ CloseTheGroupMovePanelIfAimedElsewhere();
OnPropertyChanged(nameof(GroupTarget));
- OnPropertyChanged(nameof(ShowsGroupActions));
RebuildGroupLevel();
RebuildVisibleHosts();
}
+ /// Folds the group's move panel away once the buttons under it point at something else.
+ ///
+ /// By entity id and not by row, for the reason compares ids: every
+ /// row object in the list is replaced on every reload, so a panel closed on row identity would fold up
+ /// once a minute under somebody who was still choosing a vault in it. It is cleared rather than re-aimed,
+ /// because which vault to move to is a choice about the shelf it was asked for.
+ ///
+ private void CloseTheGroupMovePanelIfAimedElsewhere()
+ {
+ if (IsMovingGroup && movingGroupId != GroupTarget?.EntityId)
+ {
+ CancelMoveGroupCommand.Execute(null);
+ }
+ }
+
partial void OnPendingDeletionChanged(DeletionRequest? value)
{
+ // Back to "keep them" on every question, including the one that disarms it. A tick is the answer to
+ // the group that was named in the sentence above it and to nothing else; carried into the next
+ // question it would delete a second group's machines on the strength of a decision about the first.
+ DeletionTakesTheHostsToo = false;
+
OnPropertyChanged(nameof(IsConfirmingDeletion));
OnPropertyChanged(nameof(IsConfirmingHostDeletion));
OnPropertyChanged(nameof(IsConfirmingGroupDeletion));
OnPropertyChanged(nameof(ShowsHostActions));
OnPropertyChanged(nameof(ShowsHostPaneActions));
- OnPropertyChanged(nameof(ShowsGroupActions));
OnPropertyChanged(nameof(ShowsItemActions));
}
@@ -7515,8 +8838,10 @@ internal sealed partial class VaultViewModel(
{
OnPropertyChanged(nameof(GroupSaveLabel));
- // Which of the two things the group editor is doing, which its header says as well as its button.
+ // Which of the two things the group editor is doing, which its header says as well as its button —
+ // and, under it, the vault a group being renamed is in, which only a rename has an answer for.
OnPropertyChanged(nameof(DrawerTitle));
+ OnPropertyChanged(nameof(DrawerSubtitle));
}
///
diff --git a/src/DodoSSH.Client.Sync/HostGroupRepository.cs b/src/DodoSSH.Client.Sync/HostGroupRepository.cs
index 8a3b05f..aacdd3b 100644
--- a/src/DodoSSH.Client.Sync/HostGroupRepository.cs
+++ b/src/DodoSSH.Client.Sync/HostGroupRepository.cs
@@ -11,11 +11,19 @@ namespace DodoSSH.Client.Sync;
/// The fifth facade over the same generic repository, and like the fourth it needed no new sync logic at all.
///
///
-/// Deleting a group does not touch the hosts in it. There is deliberately no DeleteAsync
-/// overload that unfiles its members: one user action would become N host writes, N outbox rows and N chances
-/// to merge against an edit nobody made, and the group's own tombstone can still lose a merge — by which time
-/// the membership it was clearing is gone. Hosts left holding a dangling id fall under the ungrouped heading,
-/// which is where the interface handles it. See .
+/// Deleting a group still does not touch the hosts in it, here. There is deliberately no
+/// DeleteAsync overload that unfiles its members: one call would become N host writes, N outbox rows
+/// and N chances to merge against an edit nobody made, and the group's own tombstone can still lose a merge —
+/// by which time the membership it was clearing would be gone. A host left holding a dangling id falls under
+/// the ungrouped heading, so this layer is safe whatever happens above it. See
+/// .
+///
+///
+/// What changed above it is that the deletion is no longer silent about the choice: the interface asks
+/// whether the hosts should go too, and writes them one by one through HostRepository either way —
+/// as N deletions, or as N hosts with the reference cleared. That is the same N writes, made where somebody
+/// asked for them and where the count can be shown before the fact rather than issued by a repository call
+/// that reads like one delete.
///
///
public sealed class HostGroupRepository(
@@ -48,6 +56,25 @@ public sealed class HostGroupRepository(
CancellationToken cancellationToken) =>
groups.UpdateAsync(vaultId, entityId, group, cancellationToken);
+ ///
+ ///
+ ///
+ ///
+ /// The new id matters more for a group than for anything else that can be moved, because a group is the
+ /// one item other items point at. Everything naming the old id — the hosts filed under it, the groups
+ /// nested inside it — has to be rewritten with the id this returns, or it is left pointing at a
+ /// tombstone. That rewriting is the caller's, for the reason the secret parameter is: this layer
+ /// cannot know which references cross with the group and which stay behind.
+ ///
+ ///
+ public Task MoveAsync(
+ Guid fromVaultId,
+ Guid toVaultId,
+ Guid entityId,
+ HostGroupSecret group,
+ CancellationToken cancellationToken) =>
+ groups.MoveAsync(fromVaultId, toVaultId, entityId, group, cancellationToken);
+
///
public Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken) =>
groups.DeleteAsync(vaultId, entityId, cancellationToken);
diff --git a/src/DodoSSH.Client.Sync/HostRepository.cs b/src/DodoSSH.Client.Sync/HostRepository.cs
index 14044b6..531b8a3 100644
--- a/src/DodoSSH.Client.Sync/HostRepository.cs
+++ b/src/DodoSSH.Client.Sync/HostRepository.cs
@@ -38,6 +38,15 @@ public sealed class HostRepository(
CancellationToken cancellationToken) =>
hosts.UpdateAsync(vaultId, entityId, host, cancellationToken);
+ ///
+ public Task MoveAsync(
+ Guid fromVaultId,
+ Guid toVaultId,
+ Guid entityId,
+ HostSecret host,
+ CancellationToken cancellationToken) =>
+ hosts.MoveAsync(fromVaultId, toVaultId, entityId, host, cancellationToken);
+
///
public Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken) =>
hosts.DeleteAsync(vaultId, entityId, cancellationToken);
diff --git a/src/DodoSSH.Client.Sync/VaultItemRepository.cs b/src/DodoSSH.Client.Sync/VaultItemRepository.cs
index b46ce78..bc0936b 100644
--- a/src/DodoSSH.Client.Sync/VaultItemRepository.cs
+++ b/src/DodoSSH.Client.Sync/VaultItemRepository.cs
@@ -234,6 +234,72 @@ internal sealed class VaultItemRepository(
}
}
+ ///
+ /// Moves an item into another vault.
+ ///
+ /// The vault it is in.
+ /// The vault it should be in.
+ /// The item.
+ ///
+ /// What to write into the destination. The caller's, rather than read from here, because moving is the
+ /// one operation where the item does not arrive unchanged: references to things that live in the vault
+ /// it is leaving are the mover's to resolve, and this layer has no way to know which those are.
+ ///
+ /// Cancellation token.
+ /// The id the item has in its new vault.
+ ///
+ ///
+ /// A copy and a tombstone, and it cannot be anything else. An item's payload is sealed under
+ /// its vault's key and its AAD binds the vault, the entity id and the item version — so there is no
+ /// edit that moves one, and no server call that could: the server holds ciphertext it cannot read.
+ /// What crosses is the plaintext, in this process, between an unwrap under one key and a seal under
+ /// another.
+ ///
+ ///
+ /// A new id, deliberately. Keeping it would put one entity id in two vaults, and the item table
+ /// is keyed on the type and the id rather than on the vault — so the destination's row and the
+ /// source's tombstone would be the same row, and the move would delete what it had just written.
+ /// Callers holding the old id have to take the new one back.
+ ///
+ ///
+ /// The write comes first and the tombstone second, which decides what an interruption leaves
+ /// behind: a copy in both vaults, which is visible and can be deleted, rather than a tombstone with
+ /// nothing on the other side, which is the host gone. Both are queued rather than sent, so the window
+ /// is a crash between two local writes — narrow, and worth choosing the survivable side of anyway.
+ ///
+ ///
+ /// Two activity lines, not one: a create in the destination and a delete in the source, which is what
+ /// the vaults actually record. A single "moved" line would have to be written to one of them and would
+ /// be missing from the other's history.
+ ///
+ ///
+ internal async Task MoveAsync(
+ Guid fromVaultId,
+ Guid toVaultId,
+ Guid entityId,
+ TSecret secret,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(secret);
+
+ if (fromVaultId == toVaultId)
+ {
+ throw new ArgumentException(
+ "That item is already in that vault.", nameof(toVaultId));
+ }
+
+ // Both keys before either write, so a destination this session cannot write to is refused with
+ // nothing having happened rather than after the source item has gone.
+ _ = Key(fromVaultId);
+ _ = Key(toVaultId);
+
+ var moved = await CreateAsync(toVaultId, secret, cancellationToken).ConfigureAwait(false);
+
+ await DeleteAsync(fromVaultId, entityId, cancellationToken).ConfigureAwait(false);
+
+ return moved;
+ }
+
///
/// Deletes an item.
///
diff --git a/src/DodoSSH.Contracts/DodoSshJsonContext.cs b/src/DodoSSH.Contracts/DodoSshJsonContext.cs
index e368c1c..fd1c3b4 100644
--- a/src/DodoSSH.Contracts/DodoSshJsonContext.cs
+++ b/src/DodoSSH.Contracts/DodoSshJsonContext.cs
@@ -66,6 +66,11 @@ namespace DodoSSH.Contracts;
// Registered in its own right, not only as a member of the sync DTOs: the client's local
// cache seals this record under the LocalCacheKey and needs its type info directly.
[JsonSerializable(typeof(SyncPlaintextFields))]
+
+// The event socket's only frame type. Registered although nothing else references it: frames are
+// written straight onto a WebSocket rather than through a response body, so the resolver never
+// infers it from an endpoint's signature the way it does for every DTO above.
+[JsonSerializable(typeof(VaultEvent))]
[JsonSerializable(typeof(RelayTicketRequest))]
[JsonSerializable(typeof(RelayTicketResponse))]
[JsonSerializable(typeof(RelaySessionSummary))]
diff --git a/src/DodoSSH.Contracts/Events.cs b/src/DodoSSH.Contracts/Events.cs
new file mode 100644
index 0000000..1545923
--- /dev/null
+++ b/src/DodoSSH.Contracts/Events.cs
@@ -0,0 +1,134 @@
+namespace DodoSSH.Contracts;
+
+///
+/// The event socket's protocol constants.
+///
+///
+/// The version lives in the subprotocol name rather than in the URL, for the reason ADR 0002 gives
+/// about the rest of this API: a client and a server that upgrade independently have to agree by
+/// negotiating rather than by assuming, and a WebSocket handshake already has a field for exactly
+/// that. A server that does not offer fails the handshake, which a client
+/// can act on — rather than opening a socket that then speaks a dialect it cannot read.
+///
+public static class VaultEvents
+{
+ /// The path the event socket is served from.
+ public const string Path = "/api/v1/events";
+
+ /// The only subprotocol this version speaks.
+ public const string SubProtocol = "dodossh.events.v1";
+
+ /// The /api/v1/meta feature flag advertising that this server pushes at all.
+ public const string Feature = "events";
+
+ ///
+ /// Close code for a socket whose access token has expired.
+ ///
+ ///
+ /// In the 4000–4999 range, which the WebSocket specification reserves for applications. Its own
+ /// code because it is the one close a client should answer by reconnecting immediately with a
+ /// fresh token, rather than by backing off as it would for a server that went away.
+ ///
+ public const int TokenExpiredCloseCode = 4401;
+
+ ///
+ /// Close code for a caller already holding as many sockets as it may.
+ ///
+ ///
+ /// Distinguished from because the remedy is the opposite:
+ /// reconnecting at once is what caused it. A client that meets this backs off and keeps polling.
+ ///
+ public const int TooManyConnectionsCloseCode = 4429;
+}
+
+///
+/// The kinds of event this socket carries.
+///
+///
+///
+/// Constants rather than an enum, and that is a compatibility decision rather than a style
+/// one. DodoSshJsonContext sets UseStringEnumConverter, which throws on a
+/// value it does not know — so a newer server sending a kind an older client has never heard of
+/// would not merely add an unreadable frame, it would break that client's socket. A string is
+/// ignored instead, which is what makes this list extensible. is the same
+/// shape for the same reason.
+///
+///
+/// Anything a client cannot parse must be skipped, not treated as an error. That rule is what
+/// the shared-session frames of ADR 0012 will rely on when they arrive.
+///
+///
+public static class VaultEventKinds
+{
+ /// The server accepted the socket. Always the first frame.
+ public const string Hello = "hello";
+
+ ///
+ /// A vault has changes at or before .
+ ///
+ ///
+ /// Carries no ciphertext and no item identity — the client's answer is the delta pull it would
+ /// have run on its timer anyway. See ADR 0012 for why pushing the items themselves is refused.
+ ///
+ public const string VaultChanged = "vault.changed";
+
+ ///
+ /// The set of vaults this account can reach is no longer what it was.
+ ///
+ ///
+ /// A vault shared with the caller, or a grant withdrawn. Deliberately says nothing about
+ /// which: the client re-reads the list, which is the same call it already makes at the
+ /// start of every synchronisation pass.
+ ///
+ public const string VaultsChanged = "vaults.changed";
+
+ /// Heartbeat. Whichever side receives one answers .
+ public const string Ping = "ping";
+
+ /// The answer to a .
+ public const string Pong = "pong";
+}
+
+///
+/// One frame on the event socket.
+///
+///
+///
+/// One flat record for every kind, with the fields a given kind does not use left null, rather than
+/// a polymorphic hierarchy. The set is small, the frames are tiny, and System.Text.Json
+/// polymorphism would put a second discriminator mechanism next to the string
+/// that is already the discriminator. Nothing else in DodoSSH.Contracts is polymorphic.
+///
+///
+/// Nothing here is secret, by construction. The server cannot read a vault's contents, so a
+/// notice cannot describe them; what it does disclose — that a vault changed, and when — is the same
+/// metadata ADR 0001 already accepts the server holding.
+///
+///
+/// One of . An unrecognised kind must be ignored.
+/// The vault a is about.
+///
+/// The change-log position that vault has reached. A hint for logging and for coalescing, not a
+/// cursor: cursors are opaque and HMAC-tagged, and this is neither.
+///
+///
+/// The server's clock when the frame was written. The client already measures skew against
+/// SyncPullResponse.ServerTime; this lets a socket that is quiet for other reasons keep that
+/// measurement current.
+///
+///
+/// How often the server will ping, sent with . The client uses it
+/// to decide when silence means the connection is dead rather than idle.
+///
+///
+/// How many vaults this socket is subscribed to, sent with .
+/// Diagnostic: a socket subscribed to nothing is a real state — an account with no vaults yet — and
+/// is otherwise indistinguishable from one that is quietly broken.
+///
+public sealed record VaultEvent(
+ string Kind,
+ Guid? VaultId = null,
+ long? Sequence = null,
+ DateTimeOffset? ServerTime = null,
+ int? HeartbeatSeconds = null,
+ int? VaultCount = null);
diff --git a/src/DodoSSH.Contracts/ProblemCodes.cs b/src/DodoSSH.Contracts/ProblemCodes.cs
index 1695912..5ee03b5 100644
--- a/src/DodoSSH.Contracts/ProblemCodes.cs
+++ b/src/DodoSSH.Contracts/ProblemCodes.cs
@@ -66,6 +66,16 @@ public static class ProblemCodes
///
public const string MalformedRequest = "malformed-request";
+ ///
+ /// This deployment does not push vault changes over a socket.
+ ///
+ ///
+ /// Not a failure to recover from: synchronising on a timer is the supported behaviour and the
+ /// socket only ever made it early. A client that meets this stops dialling and keeps polling. See
+ /// ADR 0012.
+ ///
+ public const string EventsUnavailable = "events-unavailable";
+
/// The relay refused the requested target. Never states why, to avoid a probe oracle.
public const string RelayTargetRejected = "relay-target-rejected";
diff --git a/src/DodoSSH.Contracts/PublicAPI.Unshipped.txt b/src/DodoSSH.Contracts/PublicAPI.Unshipped.txt
index b1b291e..30967e9 100644
--- a/src/DodoSSH.Contracts/PublicAPI.Unshipped.txt
+++ b/src/DodoSSH.Contracts/PublicAPI.Unshipped.txt
@@ -2,6 +2,7 @@
const DodoSSH.Contracts.ProblemCodes.AlreadyEnrolled = "already-enrolled" -> string!
const DodoSSH.Contracts.ProblemCodes.ClientTooOld = "client-too-old" -> string!
const DodoSSH.Contracts.ProblemCodes.EnrollmentRequired = "enrollment-required" -> string!
+const DodoSSH.Contracts.ProblemCodes.EventsUnavailable = "events-unavailable" -> string!
const DodoSSH.Contracts.ProblemCodes.Forbidden = "forbidden" -> string!
const DodoSSH.Contracts.ProblemCodes.IdempotencyKeyReuse = "idempotency-key-reuse" -> string!
const DodoSSH.Contracts.ProblemCodes.IdentityBindingInvalid = "identity-binding-invalid" -> string!
@@ -22,6 +23,16 @@ const DodoSSH.Contracts.ProblemCodes.TeamNotEmpty = "team-not-empty" -> string!
const DodoSSH.Contracts.ProblemCodes.TeamSlugTaken = "team-slug-taken" -> string!
const DodoSSH.Contracts.ProblemCodes.TypeBaseUri = "https://dodossh.dev/problems/" -> string!
const DodoSSH.Contracts.ProblemCodes.VaultConflict = "vault-conflict" -> string!
+const DodoSSH.Contracts.VaultEventKinds.Hello = "hello" -> string!
+const DodoSSH.Contracts.VaultEventKinds.Ping = "ping" -> string!
+const DodoSSH.Contracts.VaultEventKinds.Pong = "pong" -> string!
+const DodoSSH.Contracts.VaultEventKinds.VaultChanged = "vault.changed" -> string!
+const DodoSSH.Contracts.VaultEventKinds.VaultsChanged = "vaults.changed" -> string!
+const DodoSSH.Contracts.VaultEvents.Feature = "events" -> string!
+const DodoSSH.Contracts.VaultEvents.Path = "/api/v1/events" -> string!
+const DodoSSH.Contracts.VaultEvents.SubProtocol = "dodossh.events.v1" -> string!
+const DodoSSH.Contracts.VaultEvents.TokenExpiredCloseCode = 4401 -> int
+const DodoSSH.Contracts.VaultEvents.TooManyConnectionsCloseCode = 4429 -> int
DodoSSH.Contracts.AddTeamMemberRequest
DodoSSH.Contracts.AddTeamMemberRequest.$() -> DodoSSH.Contracts.AddTeamMemberRequest!
DodoSSH.Contracts.AddTeamMemberRequest.AddTeamMemberRequest(System.Guid UserId, DodoSSH.Contracts.TeamMemberRole Role, string? Email = null) -> void
@@ -686,6 +697,25 @@ DodoSSH.Contracts.UpdateVaultRequest.Equals(DodoSSH.Contracts.UpdateVaultRequest
DodoSSH.Contracts.UpdateVaultRequest.Name.get -> string!
DodoSSH.Contracts.UpdateVaultRequest.Name.init -> void
DodoSSH.Contracts.UpdateVaultRequest.UpdateVaultRequest(string! Name) -> void
+DodoSSH.Contracts.VaultEvent
+DodoSSH.Contracts.VaultEvent.$() -> DodoSSH.Contracts.VaultEvent!
+DodoSSH.Contracts.VaultEvent.Deconstruct(out string! Kind, out System.Guid? VaultId, out long? Sequence, out System.DateTimeOffset? ServerTime, out int? HeartbeatSeconds, out int? VaultCount) -> void
+DodoSSH.Contracts.VaultEvent.Equals(DodoSSH.Contracts.VaultEvent? other) -> bool
+DodoSSH.Contracts.VaultEvent.HeartbeatSeconds.get -> int?
+DodoSSH.Contracts.VaultEvent.HeartbeatSeconds.init -> void
+DodoSSH.Contracts.VaultEvent.Kind.get -> string!
+DodoSSH.Contracts.VaultEvent.Kind.init -> void
+DodoSSH.Contracts.VaultEvent.Sequence.get -> long?
+DodoSSH.Contracts.VaultEvent.Sequence.init -> void
+DodoSSH.Contracts.VaultEvent.ServerTime.get -> System.DateTimeOffset?
+DodoSSH.Contracts.VaultEvent.ServerTime.init -> void
+DodoSSH.Contracts.VaultEvent.VaultCount.get -> int?
+DodoSSH.Contracts.VaultEvent.VaultCount.init -> void
+DodoSSH.Contracts.VaultEvent.VaultEvent(string! Kind, System.Guid? VaultId = null, long? Sequence = null, System.DateTimeOffset? ServerTime = null, int? HeartbeatSeconds = null, int? VaultCount = null) -> void
+DodoSSH.Contracts.VaultEvent.VaultId.get -> System.Guid?
+DodoSSH.Contracts.VaultEvent.VaultId.init -> void
+DodoSSH.Contracts.VaultEventKinds
+DodoSSH.Contracts.VaultEvents
DodoSSH.Contracts.VaultGrantsResponse
DodoSSH.Contracts.VaultGrantsResponse.$() -> DodoSSH.Contracts.VaultGrantsResponse!
DodoSSH.Contracts.VaultGrantsResponse.Deconstruct(out System.Guid VaultId, out uint KeyGeneration, out bool RekeyRequired, out System.Collections.Generic.IReadOnlyList! Grants) -> void
@@ -877,6 +907,9 @@ override DodoSSH.Contracts.UpdateTeamRequest.ToString() -> string!
override DodoSSH.Contracts.UpdateVaultRequest.Equals(object? obj) -> bool
override DodoSSH.Contracts.UpdateVaultRequest.GetHashCode() -> int
override DodoSSH.Contracts.UpdateVaultRequest.ToString() -> string!
+override DodoSSH.Contracts.VaultEvent.Equals(object? obj) -> bool
+override DodoSSH.Contracts.VaultEvent.GetHashCode() -> int
+override DodoSSH.Contracts.VaultEvent.ToString() -> string!
override DodoSSH.Contracts.VaultGrantsResponse.Equals(object? obj) -> bool
override DodoSSH.Contracts.VaultGrantsResponse.GetHashCode() -> int
override DodoSSH.Contracts.VaultGrantsResponse.ToString() -> string!
@@ -972,6 +1005,8 @@ static DodoSSH.Contracts.UpdateTeamRequest.operator !=(DodoSSH.Contracts.UpdateT
static DodoSSH.Contracts.UpdateTeamRequest.operator ==(DodoSSH.Contracts.UpdateTeamRequest? left, DodoSSH.Contracts.UpdateTeamRequest? right) -> bool
static DodoSSH.Contracts.UpdateVaultRequest.operator !=(DodoSSH.Contracts.UpdateVaultRequest? left, DodoSSH.Contracts.UpdateVaultRequest? right) -> bool
static DodoSSH.Contracts.UpdateVaultRequest.operator ==(DodoSSH.Contracts.UpdateVaultRequest? left, DodoSSH.Contracts.UpdateVaultRequest? right) -> bool
+static DodoSSH.Contracts.VaultEvent.operator !=(DodoSSH.Contracts.VaultEvent? left, DodoSSH.Contracts.VaultEvent? right) -> bool
+static DodoSSH.Contracts.VaultEvent.operator ==(DodoSSH.Contracts.VaultEvent? left, DodoSSH.Contracts.VaultEvent? right) -> bool
static DodoSSH.Contracts.VaultGrantsResponse.operator !=(DodoSSH.Contracts.VaultGrantsResponse? left, DodoSSH.Contracts.VaultGrantsResponse? right) -> bool
static DodoSSH.Contracts.VaultGrantsResponse.operator ==(DodoSSH.Contracts.VaultGrantsResponse? left, DodoSSH.Contracts.VaultGrantsResponse? right) -> bool
static DodoSSH.Contracts.VaultGrantSummary.operator !=(DodoSSH.Contracts.VaultGrantSummary? left, DodoSSH.Contracts.VaultGrantSummary? right) -> bool
diff --git a/tests/DodoSSH.Api.Tests/ApiFixture.cs b/tests/DodoSSH.Api.Tests/ApiFixture.cs
index e78e4c9..0836578 100644
--- a/tests/DodoSSH.Api.Tests/ApiFixture.cs
+++ b/tests/DodoSSH.Api.Tests/ApiFixture.cs
@@ -1,4 +1,6 @@
using System.Net.Http.Headers;
+using System.Net.WebSockets;
+using DodoSSH.Contracts;
using DodoSSH.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
@@ -107,6 +109,34 @@ public sealed class ApiFixture : WebApplicationFactory, IAsyncLifetime
/// Opens a database scope for arranging state and asserting on it.
public AsyncServiceScope CreateScope() => Services.CreateAsyncScope();
+
+ ///
+ /// Opens the event socket as the given subject, through the real pipeline.
+ ///
+ ///
+ ///
+ /// The bearer token goes on the upgrade request, which is the whole of the socket's authorization
+ /// — see ADR 0012 — so a test that stubbed it would be testing nothing. The subprotocol is offered
+ /// because the server refuses an upgrade that does not, and that refusal is itself under test.
+ ///
+ ///
+ /// TestServer speaks WebSockets in-memory with no port and no network, so these run
+ /// wherever the rest of the suite does.
+ ///
+ ///
+ public Task ConnectEventsAsync(string subject, CancellationToken cancellationToken)
+ {
+ var token = IdentityProvider.MintToken(subject);
+ var client = Server.CreateWebSocketClient();
+
+ client.SubProtocols.Add(VaultEvents.SubProtocol);
+ // The server-side request, so the header is a raw string rather than a typed value.
+ client.ConfigureRequest = request => request.Headers.Authorization = $"Bearer {token}";
+
+ return client.ConnectAsync(
+ new Uri(Server.BaseAddress, VaultEvents.Path.TrimStart('/')),
+ cancellationToken);
+ }
}
/// Shares one host and container across every test class in the assembly.
diff --git a/tests/DodoSSH.Api.Tests/EndpointInventoryTests.cs b/tests/DodoSSH.Api.Tests/EndpointInventoryTests.cs
index b0aecd0..4a81fc0 100644
--- a/tests/DodoSSH.Api.Tests/EndpointInventoryTests.cs
+++ b/tests/DodoSSH.Api.Tests/EndpointInventoryTests.cs
@@ -56,6 +56,12 @@ public sealed class EndpointInventoryTests(ApiFixture fixture)
"POST /api/v1/vaults/{vaultId:guid}/sync/pull name=SyncPull tags=Sync policies=Enrolled anon=False",
"POST /api/v1/vaults/{vaultId:guid}/sync/push name=SyncPush tags=Sync policies=Enrolled anon=False",
+ // The WebSocket, gated exactly as sync is and for the same reason — it announces changes to
+ // vaults, and a caller who could not read one has nothing to be told about. It appears here as
+ // an ordinary route because that is what it is until the upgrade: the bearer token authorises
+ // the handshake, unlike the relay's ticket. See ADR 0012.
+ "GET /api/v1/events name=VaultEvents tags=Events policies=Enrolled anon=False",
+
// Enrolled, because the answer exists to be wrapped to and a caller with no key of their own has
// nothing to wrap and no signature to attribute it with. There is no search here — see
// DirectoryService for why an exact-match-only directory is a decision rather than a shortcut.
diff --git a/tests/DodoSSH.Api.Tests/EventsEndpointTests.cs b/tests/DodoSSH.Api.Tests/EventsEndpointTests.cs
new file mode 100644
index 0000000..6509660
--- /dev/null
+++ b/tests/DodoSSH.Api.Tests/EventsEndpointTests.cs
@@ -0,0 +1,461 @@
+using System.Net;
+using System.Net.WebSockets;
+using System.Text;
+using System.Text.Json;
+using DodoSSH.Contracts;
+using DodoSSH.Domain;
+using DodoSSH.Infrastructure;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace DodoSSH.Api.Tests;
+
+///
+/// The push channel, over a real socket through the real authentication pipeline.
+///
+///
+///
+/// The tests that matter most here are the two negatives: an unauthenticated upgrade is refused, and a
+/// change to somebody else's vault does not reach this socket. A push channel that leaked which
+/// vault ids exist and when they change would be a disclosure the pull path takes deliberate
+/// trouble to avoid — SyncPullEndpoint answers 404 rather than 403 for exactly that reason —
+/// and it would be invisible in a test that only checked that notices arrive.
+///
+///
+/// Ordering is asserted rather than absence-within-a-timeout wherever possible. "Nothing arrived in
+/// two seconds" is a test that passes on a slow machine for the wrong reason; "the first notice this
+/// socket saw was about its own vault, although another vault was written to first" is not.
+///
+///
+[Collection(ApiCollection.Name)]
+public sealed class EventsEndpointTests(ApiFixture fixture)
+{
+ private static readonly DateTimeOffset Now = new(2026, 8, 4, 12, 0, 0, TimeSpan.Zero);
+
+ ///
+ /// How long a test will wait for a frame before calling it a failure.
+ ///
+ ///
+ /// Generous, because it is not a measurement: every wait here is for something already committed,
+ /// so the only thing this bounds is how long a genuinely broken build hangs before it reports.
+ ///
+ private static readonly TimeSpan FrameTimeout = TimeSpan.FromSeconds(30);
+
+ // ---- The handshake ----
+
+ [Fact]
+ public async Task WithoutAToken_TheUpgradeIsRefused()
+ {
+ var client = fixture.Server.CreateWebSocketClient();
+ client.SubProtocols.Add(VaultEvents.SubProtocol);
+
+ var connecting = client.ConnectAsync(
+ new Uri(fixture.Server.BaseAddress, VaultEvents.Path.TrimStart('/')),
+ TestContext.Current.CancellationToken);
+
+ await Should.ThrowAsync(connecting);
+ }
+
+ [Fact]
+ public async Task BeforeEnrolling_Is403WithAnActionableCode()
+ {
+ // The same bar as sync: a caller with no identity key holds no vault key either, so every
+ // notice this socket could carry is about ciphertext they cannot read.
+ var client = fixture.CreateClientFor(NewSubject());
+
+ var response = await client.GetAsync(
+ new Uri(VaultEvents.Path, UriKind.Relative),
+ TestContext.Current.CancellationToken);
+
+ response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
+
+ var problem = await response.Content.ReadProblemAsync();
+ problem.ShouldNotBeNull();
+ problem.Code.ShouldBe(ProblemCodes.EnrollmentRequired);
+ }
+
+ [Fact]
+ public async Task APlainGet_SaysItIsAWebSocket()
+ {
+ // A person, or a client with the wrong URL. Answering with a problem document rather than a
+ // socket that closes is the difference between a diagnosable mistake and a mysterious one.
+ var client = fixture.CreateClientFor(await SeedEnrolledUserAsync());
+
+ var response = await client.GetAsync(
+ new Uri(VaultEvents.Path, UriKind.Relative),
+ TestContext.Current.CancellationToken);
+
+ response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
+
+ var problem = await response.Content.ReadProblemAsync();
+ problem.ShouldNotBeNull();
+ problem.Code.ShouldBe(ProblemCodes.MalformedRequest);
+ problem.Detail.ShouldNotBeNull().ShouldContain(VaultEvents.SubProtocol);
+ }
+
+ [Fact]
+ public async Task AnUpgradeWithoutTheSubprotocol_IsRefused()
+ {
+ // The subprotocol is this socket's version negotiation, so accepting an upgrade that did not
+ // offer it would mean answering a client in a dialect it never agreed to read.
+ var (subject, _) = await SeedUserWithVaultAsync();
+
+ var client = fixture.Server.CreateWebSocketClient();
+ client.ConfigureRequest = request => request.Headers.Authorization =
+ $"Bearer {fixture.IdentityProvider.MintToken(subject)}";
+
+ var connecting = client.ConnectAsync(
+ new Uri(fixture.Server.BaseAddress, VaultEvents.Path.TrimStart('/')),
+ TestContext.Current.CancellationToken);
+
+ await Should.ThrowAsync(connecting);
+ }
+
+ [Fact]
+ public async Task TheFirstFrameIsHello()
+ {
+ var (subject, _) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ var hello = await ReadAsync(socket, timeout.Token);
+
+ hello.Kind.ShouldBe(VaultEventKinds.Hello);
+
+ // Sent so a client knows when silence means the socket is dead rather than quiet, and so a
+ // socket following nothing — a real state, for an account with no vaults — is distinguishable
+ // from one that is broken.
+ hello.HeartbeatSeconds.ShouldNotBeNull().ShouldBeGreaterThan(0);
+ hello.VaultCount.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task MetaAdvertisesTheFeature()
+ {
+ // How a client decides whether to hold a socket open at all. Absence is not an error — it
+ // means synchronise on the timer, which is what every client did before this existed.
+ var client = fixture.CreateClient();
+
+ var meta = await (await client.GetAsync(
+ new Uri("/api/v1/meta", UriKind.Relative),
+ TestContext.Current.CancellationToken))
+ .Content.ReadContractAsync();
+
+ meta.ShouldNotBeNull();
+ meta.Features.ShouldContain(
+ feature => string.Equals(feature, VaultEvents.Feature, StringComparison.Ordinal));
+ }
+
+ // ---- Notices ----
+
+ [Fact]
+ public async Task APush_AnnouncesTheVaultToAFollowingSocket()
+ {
+ var (subject, vaultId) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ var client = fixture.CreateClientFor(subject);
+ var push = await client.PostContractAsync(PushUrl(vaultId), NewCreateBatch());
+ push.EnsureSuccessStatusCode();
+
+ var notice = await ReadUntilAsync(socket, VaultEventKinds.VaultChanged, timeout.Token);
+
+ notice.VaultId.ShouldBe(vaultId);
+
+ // A hint for logging and coalescing, never a cursor: cursors are opaque and integrity-tagged,
+ // and a client that tried to resume from this would be resuming from a number it invented.
+ notice.Sequence.ShouldNotBeNull().ShouldBeGreaterThan(0);
+ }
+
+ [Fact]
+ public async Task ANoticeCarriesNoCiphertext()
+ {
+ // The load-bearing property of the whole design. A notice says only that a vault moved; the
+ // client's answer is the delta pull it would have run on its timer anyway, which keeps exactly
+ // one code path applying changes. See ADR 0012.
+ var (subject, vaultId) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ var client = fixture.CreateClientFor(subject);
+ var batch = NewCreateBatch();
+ await client.PostContractAsync(PushUrl(vaultId), batch);
+
+ var raw = await ReadRawUntilAsync(socket, VaultEventKinds.VaultChanged, timeout.Token);
+
+ // The envelope this test pushed, as it would appear if a payload had been forwarded.
+ raw.ShouldNotContain(Convert.ToBase64String(batch.Operations[0].Payload!.Envelope));
+ raw.ShouldNotContain("payload", Case.Insensitive);
+ raw.ShouldNotContain(batch.Operations[0].EntityId.ToString());
+ }
+
+ [Fact]
+ public async Task APushToAnotherAccountsVault_IsNotAnnouncedHere()
+ {
+ // The disclosure that would matter: a socket learning that vault ids it cannot read exist,
+ // and when somebody works on them.
+ var (subject, vaultId) = await SeedUserWithVaultAsync();
+ var (stranger, strangersVaultId) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ // The stranger's write goes first, so a socket that leaked would have announced it before the
+ // one this test then waits for. Ordering, not a timeout: "nothing arrived in two seconds"
+ // passes on a slow machine for the wrong reason.
+ var strangersClient = fixture.CreateClientFor(stranger);
+ (await strangersClient.PostContractAsync(PushUrl(strangersVaultId), NewCreateBatch()))
+ .EnsureSuccessStatusCode();
+
+ var ownClient = fixture.CreateClientFor(subject);
+ (await ownClient.PostContractAsync(PushUrl(vaultId), NewCreateBatch()))
+ .EnsureSuccessStatusCode();
+
+ var notice = await ReadUntilAsync(socket, VaultEventKinds.VaultChanged, timeout.Token);
+
+ notice.VaultId.ShouldBe(vaultId);
+ notice.VaultId.ShouldNotBe(strangersVaultId);
+ }
+
+ [Fact]
+ public async Task APushThatAppliedNothing_AnnouncesNothing()
+ {
+ // A batch of pure conflicts moved no vault. Announcing one anyway would have every client on
+ // it pull for a change that is not there.
+ var (subject, vaultId) = await SeedUserWithVaultAsync();
+ var client = fixture.CreateClientFor(subject);
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ // An update to an item that does not exist: rejected as a conflict, nothing written.
+ var stale = new SyncPushRequest(
+ [
+ NewOperation(Guid.CreateVersion7(), expectedVersion: 7, envelope: [9, 9]),
+ ]);
+
+ var conflicted = await client.PostContractAsync(PushUrl(vaultId), stale);
+ conflicted.EnsureSuccessStatusCode();
+
+ var results = await conflicted.Content.ReadContractAsync();
+ results.ShouldNotBeNull();
+ results.Results[0].Status.ShouldBe(SyncOperationStatus.Conflict);
+
+ // Then a write that did land. The first notice must be that one.
+ (await client.PostContractAsync(PushUrl(vaultId), NewCreateBatch())).EnsureSuccessStatusCode();
+
+ var notice = await ReadUntilAsync(socket, VaultEventKinds.VaultChanged, timeout.Token);
+
+ notice.Sequence.ShouldNotBeNull().ShouldBeGreaterThan(0);
+ }
+
+ [Fact]
+ public async Task APing_IsAnswered()
+ {
+ var (subject, _) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ await SendAsync(socket, new VaultEvent(VaultEventKinds.Ping), timeout.Token);
+
+ var pong = await ReadUntilAsync(socket, VaultEventKinds.Pong, timeout.Token);
+
+ pong.Kind.ShouldBe(VaultEventKinds.Pong);
+ }
+
+ [Fact]
+ public async Task AFrameThisServerCannotRead_DoesNotEndTheSocket()
+ {
+ // A control channel whose failure mode is "the client polls instead" should tolerate a frame
+ // from a newer client rather than cost that client its push for the whole session.
+ var (subject, vaultId) = await SeedUserWithVaultAsync();
+
+ using var timeout = Timeout();
+ using var socket = await fixture.ConnectEventsAsync(subject, timeout.Token);
+
+ await ReadAsync(socket, timeout.Token);
+
+ await socket.SendAsync(
+ Encoding.UTF8.GetBytes("{ not json at all"),
+ WebSocketMessageType.Text,
+ endOfMessage: true,
+ timeout.Token);
+
+ var client = fixture.CreateClientFor(subject);
+ (await client.PostContractAsync(PushUrl(vaultId), NewCreateBatch())).EnsureSuccessStatusCode();
+
+ var notice = await ReadUntilAsync(socket, VaultEventKinds.VaultChanged, timeout.Token);
+
+ notice.VaultId.ShouldBe(vaultId);
+ socket.State.ShouldBe(WebSocketState.Open);
+ }
+
+ // ---- Helpers ----
+
+ /// A token that gives up rather than letting a broken build hang the suite.
+ private static CancellationTokenSource Timeout()
+ {
+ var source = CancellationTokenSource.CreateLinkedTokenSource(
+ TestContext.Current.CancellationToken);
+
+ source.CancelAfter(FrameTimeout);
+
+ return source;
+ }
+
+ private static async Task ReadAsync(WebSocket socket, CancellationToken cancellationToken)
+ {
+ var json = await ReadRawAsync(socket, cancellationToken);
+
+ return JsonSerializer.Deserialize(json, DodoSshJsonContext.Default.VaultEvent)
+ ?? throw new InvalidOperationException($"The server sent a null frame: {json}");
+ }
+
+ private static async Task ReadRawAsync(WebSocket socket, CancellationToken cancellationToken)
+ {
+ var buffer = new byte[8 * 1024];
+
+ var received = await socket.ReceiveAsync(buffer, cancellationToken);
+
+ if (received.MessageType == WebSocketMessageType.Close)
+ {
+ throw new InvalidOperationException(
+ $"The server closed the socket: {received.CloseStatus} {received.CloseStatusDescription}");
+ }
+
+ return Encoding.UTF8.GetString(buffer, 0, received.Count);
+ }
+
+ /// Reads past the frames a test does not care about — hello, and heartbeats.
+ private static async Task ReadUntilAsync(
+ WebSocket socket,
+ string kind,
+ CancellationToken cancellationToken)
+ {
+ while (true)
+ {
+ var frame = await ReadAsync(socket, cancellationToken);
+
+ if (string.Equals(frame.Kind, kind, StringComparison.Ordinal))
+ {
+ return frame;
+ }
+ }
+ }
+
+ ///
+ /// The same, but keeping the bytes.
+ ///
+ ///
+ /// Deserialising and asserting on the fields would prove only that this record has no
+ /// payload member, which is a tautology. Asserting on what actually crossed the socket is what
+ /// would catch a field added to the frame later without anybody thinking about disclosure.
+ ///
+ private static async Task ReadRawUntilAsync(
+ WebSocket socket,
+ string kind,
+ CancellationToken cancellationToken)
+ {
+ while (true)
+ {
+ var json = await ReadRawAsync(socket, cancellationToken);
+ var frame = JsonSerializer.Deserialize(json, DodoSshJsonContext.Default.VaultEvent);
+
+ if (string.Equals(frame?.Kind, kind, StringComparison.Ordinal))
+ {
+ return json;
+ }
+ }
+ }
+
+ private static Task SendAsync(WebSocket socket, VaultEvent frame, CancellationToken cancellationToken) =>
+ socket.SendAsync(
+ JsonSerializer.SerializeToUtf8Bytes(frame, DodoSshJsonContext.Default.VaultEvent),
+ WebSocketMessageType.Text,
+ endOfMessage: true,
+ cancellationToken);
+
+ private static string PushUrl(Guid vaultId) => $"/api/v1/vaults/{vaultId}/sync/push";
+
+ private static string NewSubject() => $"events-{Guid.CreateVersion7():N}";
+
+ private static SyncPushOperation NewOperation(Guid entityId, int? expectedVersion, byte[] envelope) =>
+ new(
+ Guid.CreateVersion7(),
+ SyncEntityType.Host,
+ entityId,
+ SyncOperation.Upsert,
+ expectedVersion,
+ new EncryptedPayload(envelope, [0xD, 0xE], Guid.CreateVersion7(), 1, 1),
+ new SyncPlaintextFields());
+
+ private static SyncPushRequest NewCreateBatch() =>
+ new([NewOperation(Guid.CreateVersion7(), expectedVersion: null, envelope: [1, 2, 3, 4])]);
+
+ private async Task SeedEnrolledUserAsync()
+ {
+ var subject = NewSubject();
+
+ await using var scope = fixture.CreateScope();
+ var database = scope.ServiceProvider.GetRequiredService();
+
+ var user = NewUser(subject);
+ database.Users.Add(user);
+ database.UserKeys.Add(Seed.CurrentKey(user.Id, Now));
+ await database.SaveChangesAsync();
+
+ return subject;
+ }
+
+ private async Task<(string Subject, Guid VaultId)> SeedUserWithVaultAsync()
+ {
+ var subject = NewSubject();
+
+ await using var scope = fixture.CreateScope();
+ var database = scope.ServiceProvider.GetRequiredService();
+
+ var user = NewUser(subject);
+
+ var vault = new Vault
+ {
+ Id = Guid.CreateVersion7(),
+ Name = "Personal",
+ OwnerKind = VaultOwnerKind.Personal,
+ OwnerUserId = user.Id,
+ KeyGeneration = 1,
+ CreatedAtUtc = Now,
+ UpdatedAtUtc = Now,
+ };
+
+ database.Users.Add(user);
+ database.UserKeys.Add(Seed.CurrentKey(user.Id, Now));
+ database.Vaults.Add(vault);
+ await database.SaveChangesAsync();
+
+ return (subject, vault.Id);
+ }
+
+ private UserAccount NewUser(string subject) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ Issuer = fixture.IdentityProvider.Authority,
+ Subject = subject,
+ Status = UserStatus.Active,
+ CreatedAtUtc = Now,
+ UpdatedAtUtc = Now,
+ };
+}
diff --git a/tests/DodoSSH.Client.Api.Tests/VaultEventStreamTests.cs b/tests/DodoSSH.Client.Api.Tests/VaultEventStreamTests.cs
new file mode 100644
index 0000000..3637e63
--- /dev/null
+++ b/tests/DodoSSH.Client.Api.Tests/VaultEventStreamTests.cs
@@ -0,0 +1,388 @@
+using System.Net.WebSockets;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Channels;
+using DodoSSH.Client.Api;
+using DodoSSH.Contracts;
+
+namespace DodoSSH.Client.Api.Tests;
+
+///
+/// The reconnection policy, which is what this class actually is.
+///
+///
+///
+/// A dropped socket is the ordinary case here rather than the exception — laptops sleep, proxies time
+/// out, tokens expire, servers are redeployed — so the behaviour worth covering is what happens
+/// after a failure, not the happy path. Driven through the injected connector, because the one
+/// thing a test cannot do to a real network is make it fail on cue.
+///
+///
+/// The backoff is configured down to milliseconds throughout. What is under test is the shape of the
+/// policy — does it try again, does it wait, does it stop waiting when told the token was the problem —
+/// and none of that depends on the intervals a shipped client uses.
+///
+///
+public sealed class VaultEventStreamTests
+{
+ private static readonly Uri Server = new("https://dodossh.example");
+
+ private static readonly VaultEventStreamOptions Impatient = new()
+ {
+ InitialBackoff = TimeSpan.FromMilliseconds(1),
+ MaxBackoff = TimeSpan.FromMilliseconds(5),
+ InitialSilenceTimeout = TimeSpan.FromSeconds(30),
+ };
+
+ [Fact]
+ public async Task ItDialsTheWebSocketFormOfTheServersUrl()
+ {
+ // https becomes wss, and the path is the one in the contract. Getting either wrong is a client
+ // that reconnects against a 404 for the whole session, which from outside is indistinguishable
+ // from a network that eats WebSockets.
+ var dialled = new List();
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream(
+ (url, _, _) =>
+ {
+ dialled.Add(url);
+ return Task.FromResult(socket);
+ });
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+
+ await stream.ReadAsync(Token);
+
+ dialled[0].ShouldBe(new Uri("wss://dodossh.example/api/v1/events"));
+ }
+
+ [Fact]
+ public async Task ItSendsTheBearerTokenOnTheUpgrade()
+ {
+ // The whole of this socket's authorization, unlike the relay's ticket. See ADR 0012.
+ var presented = new List();
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream(
+ (_, token, _) =>
+ {
+ presented.Add(token);
+ return Task.FromResult(socket);
+ });
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+
+ await stream.ReadAsync(Token);
+
+ presented[0].ShouldBe(StubTokens.Token);
+ }
+
+ [Fact]
+ public async Task ANoticeReachesTheReader()
+ {
+ var vaultId = Guid.CreateVersion7();
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream((_, _, _) => Task.FromResult(socket));
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, vaultId, 42));
+
+ var notice = await stream.ReadAsync(Token);
+
+ notice.Kind.ShouldBe(VaultEventKinds.VaultChanged);
+ notice.VaultId.ShouldBe(vaultId);
+ notice.Sequence.ShouldBe(42);
+ }
+
+ [Fact]
+ public async Task AHeartbeatIsAnsweredAndNotHandedToTheReader()
+ {
+ // A ping is housekeeping between the two ends. Passing it up would wake a synchronisation loop
+ // every thirty seconds for a frame that says nothing happened.
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream((_, _, _) => Task.FromResult(socket));
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.Ping, HeartbeatSeconds: 30));
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+
+ var first = await stream.ReadAsync(Token);
+
+ first.Kind.ShouldBe(VaultEventKinds.VaultChanged, "the ping should not have been forwarded");
+
+ var answered = await socket.SentAsync(Token);
+ answered.Kind.ShouldBe(VaultEventKinds.Pong);
+ }
+
+ [Fact]
+ public async Task AKindThisBuildDoesNotKnow_IsStillHandedOver()
+ {
+ // What makes the frame table extensible: this class must not decide what a newer server may
+ // say. Deciding to ignore it is the caller's, and costs that caller one redundant pass.
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream((_, _, _) => Task.FromResult(socket));
+
+ socket.Deliver(new VaultEvent("session.offered"));
+
+ var notice = await stream.ReadAsync(Token);
+
+ notice.Kind.ShouldBe("session.offered");
+ }
+
+ [Fact]
+ public async Task AFailedDial_IsRetried()
+ {
+ // No server yet, or no network. Neither is an error to report: the caller's synchronisation
+ // timer is running regardless, which is what lets this stay silent and keep trying.
+ var attempts = 0;
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream((_, _, _) =>
+ {
+ if (++attempts < 3)
+ {
+ throw new WebSocketException("no route to host");
+ }
+
+ return Task.FromResult(socket);
+ });
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+
+ var notice = await stream.ReadAsync(Token);
+
+ notice.Kind.ShouldBe(VaultEventKinds.VaultChanged);
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ADroppedSocket_IsReplaced()
+ {
+ // The case that decides whether this feature survives a laptop lid. A stream that gave up on
+ // the first close would work all morning and be silently dead after lunch.
+ var sockets = new List();
+
+ await using var stream = Stream((_, _, _) =>
+ {
+ var socket = new FakeWebSocket();
+ sockets.Add(socket);
+
+ if (sockets.Count == 1)
+ {
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+ socket.Close(WebSocketCloseStatus.EndpointUnavailable);
+ }
+ else
+ {
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 2));
+ }
+
+ return Task.FromResult(socket);
+ });
+
+ (await stream.ReadAsync(Token)).Sequence.ShouldBe(1);
+ (await stream.ReadAsync(Token)).Sequence.ShouldBe(2);
+
+ sockets.Count.ShouldBeGreaterThanOrEqualTo(2);
+ }
+
+ [Fact]
+ public async Task AnExpiredTokenClose_ReconnectsAndAsksForAFreshToken()
+ {
+ // The bound that lets a long-lived socket be authorised by a short-lived credential: the server
+ // closes at the token's expiry and the client comes straight back with a new one. The token
+ // provider being asked again is the half that matters — reconnecting with the spent token would
+ // be an unbroken loop of closes.
+ var tokens = new StubTokens();
+ var sockets = 0;
+
+ await using var stream = new VaultEventStream(
+ Server,
+ tokens,
+ TimeProvider.System,
+ (_, _, _) =>
+ {
+ var socket = new FakeWebSocket();
+
+ if (++sockets == 1)
+ {
+ socket.Close((WebSocketCloseStatus)VaultEvents.TokenExpiredCloseCode);
+ }
+ else
+ {
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 7));
+ }
+
+ return Task.FromResult(socket);
+ },
+ Impatient);
+
+ (await stream.ReadAsync(Token)).Sequence.ShouldBe(7);
+
+ tokens.Requests.ShouldBeGreaterThanOrEqualTo(2);
+ }
+
+ [Fact]
+ public async Task TryRead_TakesWhatIsWaitingAndSaysWhenNothingIs()
+ {
+ // How a caller coalesces a burst: read one, wait a moment, swallow the rest. Without this a
+ // colleague tidying a folder would produce a synchronisation pass per item.
+ var socket = new FakeWebSocket();
+
+ await using var stream = Stream((_, _, _) => Task.FromResult(socket));
+
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 1));
+ socket.Deliver(new VaultEvent(VaultEventKinds.VaultChanged, Guid.CreateVersion7(), 2));
+
+ (await stream.ReadAsync(Token)).Sequence.ShouldBe(1);
+
+ // Delivery is asynchronous, so the second may not have landed yet; this is the same
+ // wait-then-drain the caller performs.
+ await Task.Delay(TimeSpan.FromMilliseconds(200), Token);
+
+ stream.TryRead(out var queued).ShouldBeTrue();
+ queued.Sequence.ShouldBe(2);
+
+ stream.TryRead(out _).ShouldBeFalse();
+ }
+
+ [Fact]
+ public async Task AnIdleStream_NeverDelivers()
+ {
+ // What a server without the feature supplies. Waiting for ever rather than completing is the
+ // point: a caller selecting between this and a timer has to fall through to the timer, and a
+ // read that returned at once would spin that loop as fast as the machine allows.
+ using var stream = IdleVaultEventStream.Instance;
+ using var giveUp = CancellationTokenSource.CreateLinkedTokenSource(Token);
+
+ giveUp.CancelAfter(TimeSpan.FromMilliseconds(100));
+
+ await Should.ThrowAsync(
+ async () => await stream.ReadAsync(giveUp.Token));
+
+ stream.TryRead(out _).ShouldBeFalse();
+ stream.IsConnected.ShouldBeFalse();
+ }
+
+ private static CancellationToken Token => TestContext.Current.CancellationToken;
+
+ private static VaultEventStream Stream(
+ Func> connect) =>
+ new(Server, new StubTokens(), TimeProvider.System, connect, Impatient);
+
+ /// A token provider that hands out one value and counts who asked.
+ private sealed class StubTokens : IAccessTokenProvider
+ {
+ internal const string Token = "access-token";
+
+ internal int Requests { get; private set; }
+
+ public ValueTask GetAccessTokenAsync(CancellationToken cancellationToken)
+ {
+ Requests++;
+
+ return ValueTask.FromResult(Token);
+ }
+ }
+
+ ///
+ /// A socket a test writes the server's half of.
+ ///
+ ///
+ /// Frames queued with are handed out by in order;
+ /// once the queue is empty the receive waits, which is what an idle connection does. queues the close instead, so a test can script "two notices and then the server
+ /// went away" as a value rather than as a race.
+ ///
+ private sealed class FakeWebSocket : WebSocket
+ {
+ private readonly Channel inbound = Channel.CreateUnbounded();
+ private readonly Channel outbound = Channel.CreateUnbounded();
+
+ private WebSocketCloseStatus? closing;
+ private WebSocketState state = WebSocketState.Open;
+
+ public override WebSocketCloseStatus? CloseStatus => closing;
+
+ public override string? CloseStatusDescription => null;
+
+ public override WebSocketState State => state;
+
+ public override string? SubProtocol => VaultEvents.SubProtocol;
+
+ /// Queues a frame for the client to read.
+ internal void Deliver(VaultEvent frame) =>
+ inbound.Writer.TryWrite(
+ JsonSerializer.SerializeToUtf8Bytes(frame, DodoSshJsonContext.Default.VaultEvent));
+
+ /// Ends the socket, after everything already queued has been read.
+ internal void Close(WebSocketCloseStatus status)
+ {
+ closing = status;
+ inbound.Writer.TryWrite([]);
+ }
+
+ /// The next frame the client sent.
+ internal ValueTask SentAsync(CancellationToken cancellationToken) =>
+ outbound.Reader.ReadAsync(cancellationToken);
+
+ public override async Task ReceiveAsync(
+ ArraySegment buffer,
+ CancellationToken cancellationToken)
+ {
+ var frame = await inbound.Reader.ReadAsync(cancellationToken);
+
+ // The empty frame Close queues. Reported as a close, exactly as a real socket does once the
+ // peer's close frame arrives.
+ if (frame.Length == 0)
+ {
+ state = WebSocketState.Closed;
+
+ return new WebSocketReceiveResult(
+ 0, WebSocketMessageType.Close, endOfMessage: true, closing, null);
+ }
+
+ frame.CopyTo(buffer.Array!, buffer.Offset);
+
+ return new WebSocketReceiveResult(frame.Length, WebSocketMessageType.Text, endOfMessage: true);
+ }
+
+ public override Task SendAsync(
+ ArraySegment buffer,
+ WebSocketMessageType messageType,
+ bool endOfMessage,
+ CancellationToken cancellationToken)
+ {
+ var json = Encoding.UTF8.GetString(buffer.Array!, buffer.Offset, buffer.Count);
+
+ if (JsonSerializer.Deserialize(json, DodoSshJsonContext.Default.VaultEvent) is { } frame)
+ {
+ outbound.Writer.TryWrite(frame);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public override void Abort() => state = WebSocketState.Aborted;
+
+ public override Task CloseAsync(
+ WebSocketCloseStatus closeStatus,
+ string? statusDescription,
+ CancellationToken cancellationToken) => CloseOutputAsync(
+ closeStatus, statusDescription, cancellationToken);
+
+ public override Task CloseOutputAsync(
+ WebSocketCloseStatus closeStatus,
+ string? statusDescription,
+ CancellationToken cancellationToken)
+ {
+ state = WebSocketState.Closed;
+
+ return Task.CompletedTask;
+ }
+
+ public override void Dispose() => state = WebSocketState.Closed;
+ }
+}
diff --git a/tests/DodoSSH.Client.App.Layout.Tests/HostGridTests.cs b/tests/DodoSSH.Client.App.Layout.Tests/HostGridTests.cs
index c193c7a..8dfe995 100644
--- a/tests/DodoSSH.Client.App.Layout.Tests/HostGridTests.cs
+++ b/tests/DodoSSH.Client.App.Layout.Tests/HostGridTests.cs
@@ -29,10 +29,11 @@ namespace DodoSSH.Client.App.Layout.Tests;
///
/// Separate from , which measures these controls rather than driving them.
/// What is here is the one gesture that cannot be expressed as a binding and cannot be checked by
-/// measuring: a right click has to move the selection before the menu opens, because all three of
-/// that menu's commands read the vault's host selection. A menu that quietly acted on whichever host
+/// measuring: a right click has to move the selection before the menu opens, because the commands
+/// on both of that screen's menus read the vault's selection. A menu that quietly acted on whichever host
/// happened to be selected would delete the wrong machine, which is the version of this mistake worth a
-/// suite.
+/// suite — and the group cards have the same menu with a fallback behind it that makes getting it wrong
+/// quieter still.
///
///
/// A real over a real unlocked vault, for the reason the other suites here use
@@ -159,6 +160,82 @@ public sealed class HostGridTests : IAsyncLifetime
});
}
+ ///
+ /// The same rule on the cards above, where getting it wrong is quieter and worse.
+ ///
+ ///
+ ///
+ /// The host grid's menu acts on nothing when it is not aimed; this one acts on the wrong group.
+ /// GroupTarget falls back to the group whose contents are on screen when no card is selected, and
+ /// a menu that opened on a card would then offer to delete a group the pointer is nowhere near. It is
+ /// also the only way to Edit or Delete a group on the desktop, so this is the only place it is aimed.
+ ///
+ ///
+ /// Open is the one entry that takes a parameter, because OpenGroupCommand's null is a real
+ /// argument — it is ALL HOSTS. That makes its CommandParameter binding the half most likely to
+ /// rot: a path that resolves to nothing compiles, draws, and quietly leaves the grid at the top level.
+ ///
+ ///
+ [Fact]
+ public async Task ARightClickSelectsTheGroupUnderThePointer()
+ {
+ await AddGroupAsync("staging");
+
+ await OnTheGridAsync((screen, window) =>
+ {
+ var first = GroupRow(vault, "production");
+ var other = GroupRow(vault, "staging");
+
+ vault.SelectedGroup = first;
+
+ RightClick(CardFor(screen, other), window);
+
+ vault.SelectedGroup.ShouldBeSameAs(other);
+
+ var menu = screen.GroupGrid.ContextMenu.ShouldNotBeNull();
+ menu.IsOpen.ShouldBeTrue();
+
+ var items = menu.Items.OfType