Add file locking, autosync and notifications to the desktop client

Desktop milestone 3, protocol v3.

- lore-sys: lock acquire, release and status, and notification
  subscribe/unsubscribe, with their events.
- Service: locks, lock, unlock (with force) and workspace_settings
  methods; locks and notice events; error -32006 for files someone
  else holds. SUBMIT refuses those files and releases your locks on
  what it pushed unless keep_locks is set.
- Service policies: a file watcher rescans after edits, warns once per
  edited file someone else has locked, and with lock_on_edit locks
  newly modified binary files (NUL in the first 8 KB, or the binary/
  text extension lists). One notification subscription per repository
  keeps locks current and marks the workspace behind on pushes.
- Autosync (off, interval, on_change) only pulls. It holds back when
  local edits overlap remote changes, keeps them, and sets a warning.
- GUI: LOCK/UNLOCK in FILES with multi-select, LOCKED BY and LOCK in
  CHANGES with KEEP LOCKS, a LOCKS tab with UNLOCK and FORCE UNLOCK,
  the AUTO popup, notices under the header and in the tray tooltip.
  --test goes on when its warm-up sync is refused; --tab locks.
- e2e: bob gets writer access and a CLI working copy to check locks,
  lock on edit and autosync between two users.
- Docs: verified lock and notification behaviour of liblore v0.14.0,
  the protocol v3 tables, autosync, and the milestone status.
This commit is contained in:
Peterino 2026-11-26 12:07:40 -07:00
parent 4c991f3c24
commit 0e8e4a601a
23 changed files with 2317 additions and 134 deletions

View File

@ -111,6 +111,7 @@ never needs Zig. See [desktop-client.md](desktop-client.md).
| Lore binaries | The official release pinned with SHA-256 in `lore.lock`, fetched into `.lore/`; `scripts/start.sh` runs a whole deployment from `run/` | Owner, 2026-11-25 | | Lore binaries | The official release pinned with SHA-256 in `lore.lock`, fetched into `.lore/`; `scripts/start.sh` runs a whole deployment from `run/` | Owner, 2026-11-25 |
| Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) | | Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) |
| Desktop SYNC and SUBMIT | SYNC pulls and keeps local edits; SUBMIT commits and pushes the files checked in CHANGES, all by default | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) | | Desktop SYNC and SUBMIT | SYNC pulls and keeps local edits; SUBMIT commits and pushes the files checked in CHANGES, all by default | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) |
| Desktop autosync and locks | Autosync only pulls, and warns and refuses rather than overwrite overlapping local edits; the GUI locks and unlocks files, SUBMIT releases your locks, and the service refuses submits of files others hold (Lore itself does not enforce locks) | Owner, 2026-11-26; details in [desktop-client.md](desktop-client.md) |
| Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference | | Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference |
| Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed | | Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed |
| Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 | | Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 |
@ -156,8 +157,9 @@ never needs Zig. See [desktop-client.md](desktop-client.md).
management. management.
The desktop client has its own milestones, in [desktop-client.md](desktop-client.md). The desktop client has its own milestones, in [desktop-client.md](desktop-client.md).
Milestones 1 (the GUI and tray shell) and 2 (liblore in the service: real workspaces, sign-in Milestones 1 (the GUI and tray shell), 2 (liblore in the service: real workspaces, sign-in
through the forge, clone, submit and sync) are done on macOS. through the forge, clone, submit and sync) and 3 (file locking, autosync and notifications) are
done on macOS.
## Things to keep in mind ## Things to keep in mind

View File

@ -1,7 +1,8 @@
# Desktop client # Desktop client
Status: milestone 2 (liblore in the service: real workspaces, the explorer on real data, sign-in Status: milestone 3 (locking, autosync and notifications) done on macOS, after milestone 2
through the forge, clone, submit and sync) done on macOS. Last updated 2026-11-25. (liblore in the service: real workspaces, the explorer on real data, sign-in through the forge,
clone, submit and sync). Last updated 2026-11-26.
lore-forge's desktop side: a tray application and a terminal UI for people working in Lore lore-forge's desktop side: a tray application and a terminal UI for people working in Lore
repositories, both driven by one per-user **client service** that does the Lore work and runs repositories, both driven by one per-user **client service** that does the Lore work and runs
@ -19,10 +20,18 @@ policies such as autosync.
| GUI layout | A file explorer with FILES, GRAPH (revision DAG) and TREE (branch > revision > changes) tabs | Owner, 2026-11-25 | | GUI layout | A file explorer with FILES, GRAPH (revision DAG) and TREE (branch > revision > changes) tabs | Owner, 2026-11-25 |
| SYNC and SUBMIT | SYNC pulls remote changes and keeps local edits; SUBMIT asks for a message, then stages, commits and pushes | Owner, 2026-11-25 | | SYNC and SUBMIT | SYNC pulls remote changes and keeps local edits; SUBMIT asks for a message, then stages, commits and pushes | Owner, 2026-11-25 |
| What SUBMIT sends | The files checked in CHANGES, all checked by default; unchecked files stay local | Owner, 2026-11-25 | | What SUBMIT sends | The files checked in CHANGES, all checked by default; unchecked files stay local | Owner, 2026-11-25 |
| Autosync and overlapping edits | Warn and refuse: never overwrite local edits to files the remote also changed | Owner, 2026-11-26 |
| File locking | A core feature of the desktop client: the GUI lets the user lock and unlock files, and shows who holds locks | Owner, 2026-11-26 |
| Locks after SUBMIT | SUBMIT releases your locks on the files it pushed; KEEP LOCKS beside SUBMIT holds them | Owner, 2026-11-26 |
| Editing a file someone else locked | CHANGES marks it LOCKED BY <name> and unchecks it, SUBMIT refuses it, and the tray warns when the edit is first seen | Owner, 2026-11-26 |
| Where locking lives | LOCK/UNLOCK in FILES and CHANGES, a LOCKS tab, and a per-workspace lock-on-first-edit option for binary files only | Owner, 2026-11-26 |
| Milestone 3 order | Locking, autosync and notifications built together | Owner, 2026-11-26 |
| liblore bindings | Generated by bindgen in dynamic-loading mode (`lore-sys`), checked in; the service loads liblore at run time | Implementation choice | | liblore bindings | Generated by bindgen in dynamic-loading mode (`lore-sys`), checked in; the service loads liblore at run time | Implementation choice |
| Location | `desktop/` in this repository, with its own Cargo workspace and `zig build` | Owner, 2026-11-25 | | Location | `desktop/` in this repository, with its own Cargo workspace and `zig build` | Owner, 2026-11-25 |
| First milestone | GUI and tray shell, talking to a stub service | Owner, 2026-11-25 | | First milestone | GUI and tray shell, talking to a stub service | Owner, 2026-11-25 |
| Frontend protocol | JSON-RPC 2.0, one message per line, over a per-user local socket | Implementation choice | | Frontend protocol | JSON-RPC 2.0, one message per line, over a per-user local socket | Implementation choice |
| What autosync does | Pulls only; SUBMIT is the one way to push. `on_change` pulls when someone pushes, with the interval as a fallback; the interval defaults to 5 minutes | Implementation choice, open to change |
| Which files are binary | A NUL byte in the first 8 KB, overridden by per-workspace `binary`/`text` extension lists | Implementation choice, open to change |
## Why a service ## Why a service
@ -72,7 +81,7 @@ side in `desktop/zig-out/bin/`, so the GUI can start the service it was built wi
directory, then retries. directory, then retries.
- **Lifetime:** quitting a frontend leaves the service running. `shutdown` stops it. - **Lifetime:** quitting a frontend leaves the service running. `shutdown` stops it.
`forge-protocol` is the reference; it is at protocol version 2. Requests on one connection `forge-protocol` is the reference; it is at protocol version 3. Requests on one connection
run concurrently, so a long sync does not hold up the explorer's reads; answers carry the run concurrently, so a long sync does not hold up the explorer's reads; answers carry the
request's `id`. Workspace ids are `w` and a hash of the path. request's `id`. Workspace ids are `w` and a hash of the path.
@ -82,8 +91,8 @@ request's `id`. Workspace ids are `w` and a hash of the path.
| `status` | `{workspaces, uptime_s, liblore: {loaded: {version}} or {missing: {error}}, accounts}` | | `status` | `{workspaces, uptime_s, liblore: {loaded: {version}} or {missing: {error}}, accounts}` |
| `refresh {workspace}` | `{}`; rescans the working copy, then a `workspaces` event | | `refresh {workspace}` | `{}`; rescans the working copy, then a `workspaces` event |
| `sync_now {workspace}` | `{}`; `activity` events follow | | `sync_now {workspace}` | `{}`; `activity` events follow |
| `submit {workspace, message, paths}` | `{}`; stages `paths`, commits, pushes, with `activity` events. No paths: push only | | `submit {workspace, message, paths, keep_locks}` | `{}`; stages `paths`, commits, pushes, with `activity` events, then releases your locks on `paths` unless `keep_locks`. No paths: push only. Refused with `-32006` when someone else holds a lock on one of `paths` |
| `changes {workspace}` | `{changes: [{path, action, from, staged, conflict}]}` | | `changes {workspace}` | `{changes: [{path, action, from, staged, conflict, lock, lock_mine}]}` |
| `history {workspace, limit}` | `{branches, revisions}`, revisions newest first, children before parents | | `history {workspace, limit}` | `{branches, revisions}`, revisions newest first, children before parents |
| `revision {workspace, signature}` | `{revision, changes}` | | `revision {workspace, signature}` | `{revision, changes}` |
| `files {workspace, path}` | `{path, entries: [{name, path, dir, size, change, lock, lock_mine}]}`, directories first | | `files {workspace, path}` | `{path, entries: [{name, path, dir, size, change, lock, lock_mine}]}`, directories first |
@ -93,23 +102,31 @@ request's `id`. Workspace ids are `w` and a hash of the path.
| `workspace_add {path}` | The workspace, for an existing working copy | | `workspace_add {path}` | The workspace, for an existing working copy |
| `workspace_clone {url, path}` | The workspace; the clone follows as `activity` events of kind `clone` | | `workspace_clone {url, path}` | The workspace; the clone follows as `activity` events of kind `clone` |
| `workspace_remove {workspace}` | `{}`; the files stay | | `workspace_remove {workspace}` | `{}`; the files stay |
| `workspace_settings {workspace, autosync?, interval_s?, lock_on_edit?}` | The workspace; saved to `desktop.toml` |
| `locks {workspace}` | `{branch, locks: [{path, owner, owner_id, mine, locked_at_ms}]}`, yours first |
| `lock {workspace, paths}` | `{locked, already}`; `-32006` when someone else holds one |
| `unlock {workspace, paths, force}` | `{released}`; without `force`, other people's locks are refused with `-32006` |
| `shutdown` | `{}`, then the service exits | | `shutdown` | `{}`, then the service exits |
A workspace is `{id, name, path, remote, state, autosync, branch, revision, signature, changes, A workspace is `{id, name, path, remote, state, autosync, branch, revision, signature, changes,
ahead, behind, online, signed_in, error}`. An account is `{auth_url, user_id, name, expires_ms}`. ahead, behind, online, signed_in, error, interval_s, lock_on_edit, warning}`; `warning` says why
autosync is holding back. An account is `{auth_url, user_id, name, expires_ms}`.
| Event | Data | | Event | Data |
| --- | --- | | --- | --- |
| `activity` | `{workspace, kind (sync, submit, clone), phase, progress, message}` | | `activity` | `{workspace, kind (sync, submit, clone), phase, progress, message}` |
| `workspaces` | The `status` workspaces list, after any change | | `workspaces` | The `status` workspaces list, after any change |
| `login` | `{remote, phase (waiting, done, failed), url, code, message}` | | `login` | `{remote, phase (waiting, done, failed), url, code, message}` |
| `locks` | `{workspace}`: someone locked or unlocked something; read `locks` and `files` again |
| `notice` | `{workspace, message}`: something the user should know, such as a lock taken on a file they edited |
Error codes beyond JSON-RPC's: `-32000` hello first, `-32001` unsupported protocol, `-32002` Error codes beyond JSON-RPC's: `-32000` hello first, `-32001` unsupported protocol, `-32002`
no such workspace, `-32003` busy, `-32004` no liblore, `-32005` Lore refused (its message no such workspace, `-32003` busy, `-32004` no liblore, `-32005` Lore refused (its message
says why). says why), `-32006` locked by someone else (the message names the files and holders).
The service keeps its workspaces in `desktop.toml` in its config directory and rewrites it when The service keeps its workspaces in `desktop.toml` in its config directory and rewrites it when
one is added or removed. one is added, removed or changes settings. Per workspace it holds `autosync`, `interval_s`,
`lock_on_edit`, and the `binary` and `text` extension lists.
## liblore ## liblore
@ -207,21 +224,103 @@ or submit finishing.
LIST, a repository from the list, INTO a folder, CLONE. LIST, a repository from the list, INTO a folder, CLONE.
- **Sign-in:** a banner with the device code, OPEN (the forge's device page, also opened - **Sign-in:** a banner with the device code, OPEN (the forge's device page, also opened
automatically) and COPY CODE. automatically) and COPY CODE.
- **Workspace bar:** branch, revision, AHEAD, BEHIND or OFFLINE, SIGN IN when signed out, - **Workspace bar:** branch, revision, AHEAD, BEHIND or OFFLINE, LOCK ON EDIT, SIGN IN when
progress, SYNC. signed out, progress, AUTO and SYNC. AUTO shows the autosync mode (OFF, 5M, ON CHANGE) and
- **FILES:** breadcrumbs with UP and REFRESH, a folder tree, and a list with size and state opens a popup with the mode, the interval in minutes, and LOCK BINARY FILES ON FIRST EDIT.
(NEW, MOD, DEL, MOVE for working-copy changes, LOCK for locks: blue when yours). Below, the Autosync's warning shows under the bar.
selected file's revisions. - **Notices** from the service show as dismissable lines under the header, and the newest one
and any autosync warnings go in the tray tooltip. UHDK has no OS notifications.
- **FILES:** breadcrumbs with UP and REFRESH, LOCK and UNLOCK for the chosen files (ctrl- or
shift-click chooses several), a folder tree, and a list with size and state (NEW, MOD, DEL,
MOVE for working-copy changes, LOCK for locks: blue when yours). Below, the selected file's
holder and lock time, and its revisions.
- **GRAPH:** revisions newest first with lanes. Each lane holds the revision it leads to; a - **GRAPH:** revisions newest first with lanes. Each lane holds the revision it leads to; a
revision takes the first lane leading to it, and a parent already waited for is joined revision takes the first lane leading to it, and a parent already waited for is joined
rather than given a new lane. Lines take the branch's colour, merges are hollow nodes, and rather than given a new lane. Lines take the branch's colour, merges are hollow nodes, and
branch heads carry a tag. Below, the selected revision's parents and changes. The web GRAPH branch heads carry a tag. Below, the selected revision's parents and changes. The web GRAPH
uses the same layout, ported to Rust in `crates/forge-web/src/pages/graph.rs`. uses the same layout, ported to Rust in `crates/forge-web/src/pages/graph.rs`.
- **TREE:** branches, each opening to its revisions, each opening to its changes. - **TREE:** branches, each opening to its revisions, each opening to its changes.
- **CHANGES:** local changes with a checkbox each (ALL, NONE, RESCAN), a MESSAGE, and SUBMIT; - **CHANGES:** local changes with a checkbox each (ALL, NONE, RESCAN, LOCK for the chosen
PUSH when nothing is changed but the workspace is ahead. unlocked files), a MESSAGE, SUBMIT and KEEP LOCKS; PUSH when nothing is changed but the
workspace is ahead. A file someone else locked shows LOCKED BY <name> and cannot be checked.
- **LOCKS:** every lock on the current branch, yours first, with REFRESH, UNLOCK for yours and
FORCE UNLOCK for other people's. FORCE UNLOCK is offered to everyone; the server refuses
anyone without `admin`.
- A change or history row jumps to the file or the revision. - A change or history row jumps to the file or the revision.
## Locks
The owner counts locking among the desktop client's main features: for binary assets that
cannot be merged, a user takes the file's lock before editing it.
Verified by calling v0.14.0's liblore against a real `loreserver` and lore-forge, with two
users who both hold `write` (`lore-sys/examples/probe.rs`), 2026-11-26:
- **Locks are advisory. Lore does not enforce them on push.** bob pushed a change to a file
alice had locked, and it was accepted. Only clients that check locks stop such a push, so the
desktop client checks before every submit.
- **Pushing does not release a lock.** Releasing is a separate call.
- `lore_lock_file_acquire {paths, branch}` takes a branch name, a branch id, or nothing (the
current branch). Acquiring again reports the path as already ours. Taking a lock someone else
holds fails with "resource already locked". A path that does not exist fails with code 83
("Node not found"). An untracked file and a directory can both be locked; a directory's lock
covers only that path, not what is in it.
- `lore_lock_file_release` with no owner releases the caller's own lock, reporting `not_found`
when there was none. Releasing another user's lock needs their user id as `owner_id`. A writer
is refused ("resource locked by somebody else"). The repository's owner may do it.
- Locks report their holder as a user id; the service turns ids into names.
- `lore_notification_subscribe` runs until `lore_notification_unsubscribe` is called from
another thread of the same process; then it ends at once. Meanwhile it reports locks,
unlocks, pushes (with the pusher's id and the new revision) and branches created or deleted.
An unlock notification names who released the lock, not who held it. Re-acquiring a lock you
already hold also sends a lock notification, with no paths and a zero branch.
- **One subscription per repository per process.** A second `notification_subscribe` for the
same repository replaces the first, and unsubscribing ends both. The service therefore keeps
one subscription per repository and hands its events to every workspace of that repository.
- **Names.** liblore names the signed-in user by username (`preferred_username`, "alice") and
other users by display name from UserService ("Bob Example"). The service shows what liblore
returns, so your own name and others' differ in kind.
Per [namespaces-and-access.md](namespaces-and-access.md), read in Lore's lock service and
authorizer: `write` takes locks, and `admin` also releases other people's.
As built, following the owner's choices of 2026-11-26 (the GUI side is under
[Explorer](#explorer)):
- **Enforcement is the service's.** SUBMIT, and `lock`/`unlock` without `force`, are refused with
`-32006` when someone else holds a lock on a file in them. Clients that do not check, such as
the `lore` CLI, can still push over a lock; stopping that needs enforcement in Lore itself.
- **SUBMIT** collects your locks on the files it pushes before pushing, then releases them,
unless KEEP LOCKS is ticked. Its message ends with what it released.
- **Editing a file someone else holds.** After each scan the service checks newly edited files
against the locks and sends a `notice` once per file ("d.txt is locked by Bob Example; your
edits stay local until the lock is released"). When someone locks a file you have already
edited, the notice says so.
- **Lock on first edit:** a per-workspace option, for modified binary files only. When a scan
finds one edited and unlocked, the service takes the lock.
- **Which files are binary.** Lore has no file-type notion in `lore.h`, so the service decides:
a NUL byte in the first 8 KB means binary (as git does), and the per-workspace `binary` and
`text` extension lists override that.
- **Watching.** Per workspace the service watches the working copy's files (ignoring `.lore`
and `.urc*`), rescans after 800 ms of quiet, and then runs the checks above. Notifications
keep the lock list current; a lock or unlock sends the `locks` event.
## Autosync
- **Modes:** `off`; `interval`, a sync every `interval_s` (default 300, at least 10); and
`on_change`, a sync as soon as a push notification arrives for the workspace's branch, with the
interval as a fallback. Autosync only pulls; SUBMIT is the one way to push.
- **Behind comes from notifications.** A status scan does not learn of remote pushes
(`remote_ahead` stays stale, verified with v0.14.0), so BEHIND is set when a BranchPushed
notification names a head the workspace has not reached, and cleared once it has.
- **Overlapping edits.** Before syncing, the service diffs the workspace's revision against the
remote head (`revision_diff`) and intersects that with the local changes. Any overlap holds
the sync back and sets the workspace's `warning` ("autosync held back: local edits to a.txt
overlap remote changes; submit or revert them"), which also goes out as a `notice`. Lore's own
refusal (code 44) is handled the same way, in case the check misses something. The edits are
never touched; the warning clears after the next successful sync.
- Autosync skips workspaces that are busy, offline or signed out.
## Verified so far ## Verified so far
On macOS (Apple silicon), 2026-11-25: On macOS (Apple silicon), 2026-11-25:
@ -242,6 +341,23 @@ On macOS (Apple silicon), 2026-11-25:
and the sign-in banner has not been automated. and the sign-in banner has not been automated.
- The tray item registers: the window offers HIDE, which it does only when UHDK reports the - The tray item registers: the window offers HIDE, which it does only when UHDK reports the
tray available. tray available.
On macOS, 2026-11-26, milestone 3: `scripts/e2e-lore.sh` also gives bob writer access and a
CLI working copy, then checks through the service:
- lock, re-lock reported as already held, and the LOCKS listing;
- bob's CLI lock reaching alice's service by notification, the notice for her edit, the change's
LOCKED BY fields, and submit, lock and unlock refused with `-32006`;
- FORCE UNLOCK by alice, the repository's owner;
- SUBMIT releasing alice's lock, and lock on first edit taking `art.bin` but not `e.txt`;
- `on_change` autosync pulling bob's push, and an overlapping edit holding autosync back with a
notice and a warning while alice's edit stays.
With a held run and bob holding a lock on a file alice edited, `--screenshot --tab` captured
FILES (LOCK and UNLOCK), CHANGES (LOCKED BY, the unticked row, KEEP LOCKS) and LOCKS drawn from
real data. Clicking LOCK, UNLOCK and FORCE UNLOCK, the AUTO popup, and the notice banner have
not been exercised in the GUI; the service side of each is covered by the e2e. `--test` now
goes on when its warm-up sync is refused, so such a state can be captured.
- **A sleeping display.** On macOS the window cannot open while the display sleeps, most - **A sleeping display.** On macOS the window cannot open while the display sleeps, most
likely because UHDK's display link needs an active display. `--test` then fails with "open likely because UHDK's display link needs an active display. `--test` then fails with "open
session: Operating system error"; waking the display (`caffeinate -u`) is enough. session: Operating system error"; waking the display (`caffeinate -u`) is enough.
@ -278,8 +394,12 @@ Found while building:
- Protocol v2 with the explorer's methods; the sample repository is gone. - Protocol v2 with the explorer's methods; the sample repository is gone.
- Real status, sync, submit of chosen files, sign-in through the forge, the repository - Real status, sync, submit of chosen files, sign-in through the forge, the repository
list, clone, and adding or forgetting workspaces from the GUI. list, clone, and adding or forgetting workspaces from the GUI.
3. **Policies.** Autosync (on an interval, on file change, never), with conflict handling to 3. **Locking and policies.** Done on macOS.
design. Then notifications from `NotificationService`. - Locking from the GUI: see [Locks](#locks).
- Autosync (on an interval, on a push, never): see [Autosync](#autosync). When local edits
overlap remote changes it refuses, keeps the edits, and warns in the GUI and the tray.
- Notifications from `NotificationService`: new revisions and lock changes.
- Protocol v3.
4. **TUI.** ratatui over the same protocol. 4. **TUI.** ratatui over the same protocol.
5. **lore-forge integration.** Sign-in and the repository list came in milestone 2. Left: 5. **lore-forge integration.** Sign-in and the repository list came in milestone 2. Left:
permissions from the forge (what the user may push or lock), and links between the GUI and permissions from the forge (what the user may push or lock), and links between the GUI and
@ -287,10 +407,9 @@ Found while building:
## Open ## Open
- What SYNC and autosync do when local edits overlap remote changes. Today sync refuses - Autosync's default interval (5 minutes for now), and whether autosync should ever push.
(Lore's code 44) and says to submit or revert first. - Server-side lock enforcement: Lore accepts pushes over locks, so only desktop clients honour
- Locking from the GUI: Lore has the operations, and FILES shows locks, but there is no LOCK or them. Enforcing them would need a hook in Lore or a check in lore-forge's authorizer.
UNLOCK yet.
- Whether the service should start at login (launch agent, systemd user unit, Run key), and - Whether the service should start at login (launch agent, systemd user unit, Run key), and
who installs that. who installs that.
- Packaging and signing per platform. - Packaging and signing per platform.

View File

@ -25,8 +25,11 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or
directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push. directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push.
It also drives the desktop `forge-service` through `scripts/desktop-e2e.py`, so run it after It also drives the desktop `forge-service` through `scripts/desktop-e2e.py`, so run it after
service changes too; `NO_DESKTOP=1` skips that. Its logins use `LORE_AUTH_STORE=fallback`, service changes too; `NO_DESKTOP=1` skips that. That part signs in a second user, bob, with a
so it never asks for the keychain. CLI working copy, to check locks and autosync between two users. The service logs at
`RUST_LOG` (default `info,forge_service=debug`) to `stdout.log` in its directory, which the
script prints on failure. Its logins use `LORE_AUTH_STORE=fallback`, so it never asks for
the keychain.
- To move Lore: `scripts/fetch-lore.sh --pin vX.Y.Z`, then the e2e test, then update the version - To move Lore: `scripts/fetch-lore.sh --pin vX.Y.Z`, then the e2e test, then update the version
recorded in [lore-integration.md](.ai/designs/lore-integration.md). If `lore.h` changed, recorded in [lore-integration.md](.ai/designs/lore-integration.md). If `lore.h` changed,
regenerate the bindings (`cargo run -p lore-sys-gen -- .lore/vX.Y.Z/lore.h` in `desktop/`, regenerate the bindings (`cargo run -p lore-sys-gen -- .lore/vX.Y.Z/lore.h` in `desktop/`,
@ -34,10 +37,11 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
- The desktop client in `desktop/` builds separately with Zig 0.17.1 and Cargo: - The desktop client in `desktop/` builds separately with Zig 0.17.1 and Cargo:
- `cd desktop && zig build test` runs its Rust tests and the GUI's self-test against a - `cd desktop && zig build test` runs its Rust tests and the GUI's self-test against a
private service; private service. On macOS the window cannot open while the display sleeps ("open session:
Operating system error"); `caffeinate -u -t 2` first wakes it;
- `zig build check -Dtarget=x86_64-windows-gnu` cross-compiles the GUI; - `zig build check -Dtarget=x86_64-windows-gnu` cross-compiles the GUI;
- `cargo clippy --all-targets` in `desktop/` should stay clean; - `cargo clippy --all-targets` in `desktop/` should stay clean;
- `forge-desktop --test --config-from <toml> --screenshot <png> [--tab files|graph|tree|changes]` - `forge-desktop --test --config-from <toml> --screenshot <png> [--tab files|graph|tree|changes|locks]`
captures the window, for checking UI changes without screen-recording permission. With captures the window, for checking UI changes without screen-recording permission. With
workspaces it syncs the first and waits for the tab's data, so it needs a live server and workspaces it syncs the first and waits for the tab's data, so it needs a live server and
a login (`LORE_AUTH_PATH`); a held e2e run (`HOLD=1 KEEP_WORK=1`) provides both. a login (`LORE_AUTH_PATH`); a held e2e run (`HOLD=1 KEEP_WORK=1`) provides both.

117
desktop/Cargo.lock generated
View File

@ -208,6 +208,7 @@ dependencies = [
"clap", "clap",
"forge-protocol", "forge-protocol",
"lore-sys", "lore-sys",
"notify",
"serde", "serde",
"serde_json", "serde_json",
"tempfile", "tempfile",
@ -256,6 +257,26 @@ dependencies = [
"hashbrown", "hashbrown",
] ]
[[package]]
name = "inotify"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
dependencies = [
"bitflags",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "is_terminal_polyfill" name = "is_terminal_polyfill"
version = "1.70.2" version = "1.70.2"
@ -277,6 +298,26 @@ version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "kqueue"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
dependencies = [
"kqueue-sys",
"libc",
]
[[package]]
name = "kqueue-sys"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
dependencies = [
"bitflags",
"libc",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.5.1" version = "1.5.1"
@ -353,6 +394,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [ dependencies = [
"libc", "libc",
"log",
"wasi", "wasi",
"windows-sys", "windows-sys",
] ]
@ -367,6 +409,34 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "notify"
version = "8.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674"
dependencies = [
"bitflags",
"inotify",
"kqueue",
"libc",
"log",
"mio",
"notify-types",
"objc2-core-foundation",
"objc2-core-services",
"walkdir",
"windows-sys",
]
[[package]]
name = "notify-types"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@ -376,6 +446,25 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
]
[[package]]
name = "objc2-core-services"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
dependencies = [
"libc",
"objc2-core-foundation",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@ -476,6 +565,15 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.229" version = "1.0.229"
@ -764,12 +862,31 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "walkdir"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403"
dependencies = [
"same-file",
"winapi-util",
]
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.11.1+wasi-snapshot-preview1" version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"

View File

@ -17,6 +17,7 @@ publish = false
forge-protocol = { path = "protocol" } forge-protocol = { path = "protocol" }
lore-sys = { path = "lore-sys" } lore-sys = { path = "lore-sys" }
libloading = "0.8" libloading = "0.8"
notify = "8"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "signal", "fs"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "signal", "fs"] }

View File

@ -112,6 +112,56 @@ const char *StateLabel(model::Action action, ImU32 &colour) {
} }
} }
// The pixel checkbox: an inset square, filled when on.
void PixelCheck(ImVec2 p, bool on, bool enabled = true) {
Box(p, {p.x + 12, p.y + 12}, enabled ? theme::kMuted : theme::kRaised);
Box({p.x + 1, p.y + 1}, {p.x + 11, p.y + 11}, theme::kInk);
if (on)
Box({p.x + 3, p.y + 3}, {p.x + 9, p.y + 9}, enabled ? theme::kForge : theme::kRaised);
}
// A checkbox with a label after it, as tall as a button. True when clicked.
bool CheckBox(const char *label, bool &value, bool enabled = true) {
ImVec2 p = ImGui::GetCursorScreenPos();
float h = ImGui::GetFrameHeight();
ImGui::BeginDisabled(!enabled);
bool clicked = ImGui::InvisibleButton(label, {20 + ImGui::CalcTextSize(label).x, h});
ImGui::EndDisabled();
if (clicked)
value = !value;
PixelCheck({p.x, std::floor(p.y + (h - 12) / 2)}, value, enabled);
ImU32 colour = !enabled ? theme::kMuted : ImGui::IsItemHovered() ? theme::kSpark : theme::kPaper;
theme::TextAt({p.x + 20, std::floor(p.y + (h - ImGui::GetTextLineHeight()) / 2)}, colour, label);
return clicked;
}
float CheckBoxWidth(const char *label) {
return 20 + ImGui::CalcTextSize(label).x;
}
// Whether a click adds to a selection instead of replacing it.
bool Adding() {
const ImGuiIO &io = ImGui::GetIO();
return io.KeyCtrl || io.KeySuper || io.KeyShift;
}
// A click on a row of a list with several rows chosen at once.
void Choose(std::set<std::string> &chosen, const std::string &key) {
if (!Adding()) {
chosen = {key};
} else if (!chosen.erase(key)) {
chosen.insert(key);
}
}
const char *AutosyncLabel(const std::string &autosync) {
if (autosync == "interval")
return "INTERVAL";
if (autosync == "on_change")
return "ON CHANGE";
return "OFF";
}
} // namespace } // namespace
void Explorer::SetTab(const std::string &name) { void Explorer::SetTab(const std::string &name) {
@ -121,6 +171,8 @@ void Explorer::SetTab(const std::string &name) {
tab_ = Tab::Tree; tab_ = Tab::Tree;
else if (name == "changes") else if (name == "changes")
tab_ = Tab::Changes; tab_ = Tab::Changes;
else if (name == "locks")
tab_ = Tab::Locks;
else else
tab_ = Tab::Files; tab_ = Tab::Files;
} }
@ -247,8 +299,17 @@ void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, Expl
if (ws.state != "unknown" && !ws.online) if (ws.state != "unknown" && !ws.online)
flag("OFFLINE", theme::kRed); flag("OFFLINE", theme::kRed);
if (ws.lock_on_edit)
flag("LOCK ON EDIT", theme::kBlue);
bool busy = ws.state == "syncing"; bool busy = ws.state == "syncing";
float button_x = std::floor(right - theme::ButtonWidth("SYNC")); std::string autosync = "AUTO ";
if (ws.autosync == "interval")
autosync += ws.interval_s % 60 ? std::to_string(ws.interval_s) + "S" : std::to_string(ws.interval_s / 60) + "M";
else
autosync += AutosyncLabel(ws.autosync);
float autosync_w = theme::ButtonWidth(autosync.c_str());
float button_x = std::floor(right - theme::ButtonWidth("SYNC") - autosync_w - 12);
bool sign_in = ws.state != "unknown" && ws.online && !ws.signed_in; bool sign_in = ws.state != "unknown" && ws.online && !ws.signed_in;
if (sign_in) if (sign_in)
button_x -= theme::ButtonWidth("SIGN IN") + 12; button_x -= theme::ButtonWidth("SIGN IN") + 12;
@ -265,6 +326,14 @@ void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, Expl
host.SignIn(); host.SignIn();
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
} }
if (theme::Button(autosync.c_str(), connected)) {
interval_min_ = int(std::max<uint64_t>(1, ws.interval_s / 60));
ImGui::OpenPopup("autosync");
}
if (ImGui::IsItemHovered() && !ImGui::IsPopupOpen("autosync"))
ImGui::SetTooltip("autosync pulls others' revisions; it never pushes");
DrawAutosync(ws, host, connected);
ImGui::SameLine(0, 12);
if (theme::Button("SYNC", connected && !busy && ws.signed_in, !sign_in)) if (theme::Button("SYNC", connected && !busy && ws.signed_in, !sign_in))
host.Sync(); host.Sync();
ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 6}); ImGui::SetCursorScreenPos({p.x, p.y + ImGui::GetFrameHeight() + 2 + 6});
@ -273,9 +342,54 @@ void Explorer::DrawBar(const model::Workspace &ws, const model::Repo &repo, Expl
ImGui::TextWrapped("%s", ws.error.c_str()); ImGui::TextWrapped("%s", ws.error.c_str());
ImGui::PopStyleColor(); ImGui::PopStyleColor();
} }
if (!ws.warning.empty()) {
ImGui::PushStyleColor(ImGuiCol_Text, theme::kSpark);
ImGui::TextWrapped("%s", ws.warning.c_str());
ImGui::PopStyleColor();
}
Gap(4); Gap(4);
} }
// The AUTO button's popup: when to pull, and locking binary files on their first edit.
void Explorer::DrawAutosync(const model::Workspace &ws, ExplorerHost &host, bool connected) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12, 10});
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 8});
if (!ImGui::BeginPopup("autosync")) {
ImGui::PopStyleVar(2);
return;
}
theme::TextColoured(theme::kMuted, "AUTOSYNC");
const char *modes[] = {"off", "interval", "on_change"};
for (size_t i = 0; i < 3; ++i) {
if (i)
ImGui::SameLine(0, 8);
if (theme::Button(AutosyncLabel(modes[i]), connected, ws.autosync == modes[i]) && ws.autosync != modes[i])
host.SetAutosync(modes[i], uint64_t(interval_min_) * 60);
}
ImGui::AlignTextToFramePadding();
theme::TextColoured(ws.autosync == "off" ? theme::kRaised : theme::kMuted, "EVERY");
ImGui::SameLine(0, 8);
ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk);
ImGui::SetNextItemWidth(110);
ImGui::InputInt("##minutes", &interval_min_, 1, 5);
ImGui::PopStyleColor();
interval_min_ = std::clamp(interval_min_, 1, 24 * 60);
if (ImGui::IsItemDeactivatedAfterEdit() || (ImGui::IsItemEdited() && !ImGui::IsItemActive()))
host.SetAutosync(ws.autosync, uint64_t(interval_min_) * 60);
ImGui::SameLine(0, 8);
theme::TextColoured(ws.autosync == "off" ? theme::kRaised : theme::kMuted, "MIN");
theme::TextColoured(theme::kMuted, ws.autosync == "on_change" ? "pulls when someone pushes; checks every interval too"
: ws.autosync == "interval" ? "pulls every interval"
: "pulls only on SYNC");
theme::TextColoured(theme::kMuted, "held back while your edits overlap theirs");
theme::Rule();
bool lock_on_edit = ws.lock_on_edit;
if (CheckBox("LOCK BINARY FILES ON FIRST EDIT", lock_on_edit, connected))
host.SetLockOnEdit(lock_on_edit);
ImGui::EndPopup();
ImGui::PopStyleVar(2);
}
void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected) { void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected) {
if (workspace_ != ws.id) { if (workspace_ != ws.id) {
workspace_ = ws.id; workspace_ = ws.id;
@ -285,6 +399,9 @@ void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost
open_dirs_.clear(); open_dirs_.clear();
open_branches_.clear(); open_branches_.clear();
open_revisions_.clear(); open_revisions_.clear();
marked_.clear();
lock_marked_.clear();
keep_locks_ = false;
graph_key_ = 0; graph_key_ = 0;
graph_.clear(); graph_.clear();
} }
@ -312,6 +429,12 @@ void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost
std::string changes = ws.changes ? "CHANGES " + std::to_string(ws.changes) : "CHANGES"; std::string changes = ws.changes ? "CHANGES " + std::to_string(ws.changes) : "CHANGES";
if (theme::Tab(changes.c_str(), tab_ == Tab::Changes)) if (theme::Tab(changes.c_str(), tab_ == Tab::Changes))
tab_ = Tab::Changes; tab_ = Tab::Changes;
ImGui::SameLine();
if (connected && repo.locks_state == model::Load::None)
host.LoadLocks();
std::string locks = repo.locks.empty() ? "LOCKS" : "LOCKS " + std::to_string(repo.locks.size());
if (theme::Tab(locks.c_str(), tab_ == Tab::Locks))
tab_ = Tab::Locks;
ImGui::PopStyleVar(); ImGui::PopStyleVar();
ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel); ImGui::PushStyleColor(ImGuiCol_ChildBg, theme::kPanel);
@ -321,10 +444,11 @@ void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost
theme::TextColoured(theme::kMuted, "no service"); theme::TextColoured(theme::kMuted, "no service");
} else { } else {
switch (tab_) { switch (tab_) {
case Tab::Files: DrawFiles(repo, host); break; case Tab::Files: DrawFiles(ws, repo, host); break;
case Tab::Graph: DrawGraph(repo, host); break; case Tab::Graph: DrawGraph(repo, host); break;
case Tab::Tree: DrawTree(repo, host); break; case Tab::Tree: DrawTree(repo, host); break;
case Tab::Changes: DrawChanges(ws, repo, host, connected); break; case Tab::Changes: DrawChanges(ws, repo, host, connected); break;
case Tab::Locks: DrawLocks(ws, repo, host, connected); break;
} }
if (tab_ == Tab::Files) if (tab_ == Tab::Files)
DrawFileDetails(ws, repo, host); DrawFileDetails(ws, repo, host);
@ -336,15 +460,33 @@ void Explorer::Draw(const model::Workspace &ws, model::Repo &repo, ExplorerHost
// ---- Files // ---- Files
void Explorer::DrawFiles(model::Repo &repo, ExplorerHost &host) { void Explorer::DrawFiles(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host) {
if (repo.dir_state[dir_] == model::Load::None) if (repo.dir_state[dir_] == model::Load::None)
host.LoadDir(dir_); host.LoadDir(dir_);
const ImVec2 row = ImGui::GetCursorScreenPos();
const float row_right = row.x + ImGui::GetContentRegionAvail().x;
if (theme::Button("UP", !dir_.empty())) if (theme::Button("UP", !dir_.empty()))
dir_ = Parent(dir_); dir_ = Parent(dir_);
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
if (theme::Button("REFRESH")) if (theme::Button("REFRESH"))
host.Refresh(); host.Refresh();
float y = ImGui::GetItemRectMin().y + 4; float y = ImGui::GetItemRectMin().y + 4;
// LOCK and UNLOCK act on the chosen files, right-aligned on this row.
std::vector<std::string> to_lock, to_unlock;
for (const auto &path : marked_) {
const model::FileEntry *e = repo.FindEntry(path);
if (!e || e->change == model::Action::Delete)
continue;
if (e->lock.empty())
to_lock.push_back(path);
else if (e->lock_mine)
to_unlock.push_back(path);
}
bool can = ws.signed_in && ws.state != "syncing";
float buttons_x = std::floor(row_right - theme::ButtonWidth("LOCK") - theme::ButtonWidth("UNLOCK") - 12);
float crumbs_right = buttons_x - 16;
ImGui::PushClipRect({row.x, row.y}, {crumbs_right, row.y + ImGui::GetFrameHeight() + 2}, true);
std::vector<std::pair<std::string, std::string>> crumbs = {{"/", ""}}; std::vector<std::pair<std::string, std::string>> crumbs = {{"/", ""}};
for (std::string d = dir_; !d.empty(); d = Parent(d)) for (std::string d = dir_; !d.empty(); d = Parent(d))
crumbs.insert(crumbs.begin() + 1, {BaseName(d), d}); crumbs.insert(crumbs.begin() + 1, {BaseName(d), d});
@ -365,6 +507,15 @@ void Explorer::DrawFiles(model::Repo &repo, ExplorerHost &host) {
theme::TextAt(at, ImGui::IsItemHovered() ? theme::kSpark : last ? theme::kPaper : theme::kMuted, label.c_str()); theme::TextAt(at, ImGui::IsItemHovered() ? theme::kSpark : last ? theme::kPaper : theme::kMuted, label.c_str());
ImGui::PopID(); ImGui::PopID();
} }
ImGui::PopClipRect();
ImGui::SetCursorScreenPos({buttons_x, row.y});
if (theme::Button("LOCK", can && !to_lock.empty()))
host.Lock(to_lock);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("lock the chosen files so nobody else submits them; ctrl-click chooses several");
ImGui::SameLine(0, 12);
if (theme::Button("UNLOCK", can && !to_unlock.empty()))
host.Unlock(to_unlock, false);
Gap(6); Gap(6);
const float details_h = 156; const float details_h = 156;
@ -442,13 +593,15 @@ void Explorer::DrawFileList(model::Repo &repo, ExplorerHost &host) {
std::string open_dir; std::string open_dir;
for (const auto &e : listed->second) { for (const auto &e : listed->second) {
ImGui::PushID(e.name.c_str()); ImGui::PushID(e.name.c_str());
if (theme::Row("entry", selected_path_ == e.path, kRowH)) if (theme::Row("entry", marked_.count(e.path) || selected_path_ == e.path, kRowH)) {
selected_path_ = e.path; selected_path_ = e.path;
Choose(marked_, e.path);
}
bool hovered = ImGui::IsItemHovered(); bool hovered = ImGui::IsItemHovered();
if (hovered && e.dir && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) if (hovered && e.dir && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
open_dir = e.path; open_dir = e.path;
if (hovered && !e.lock.empty()) if (hovered && !e.lock.empty())
ImGui::SetTooltip("locked by %s", e.lock.c_str()); ImGui::SetTooltip("locked by %s", e.lock_mine ? "you" : e.lock.c_str());
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
float y = p.y + 2; float y = p.y + 2;
if (e.dir) if (e.dir)
@ -505,8 +658,11 @@ void Explorer::DrawFileDetails(const model::Workspace &ws, model::Repo &repo, Ex
ImU32 colour = 0; ImU32 colour = 0;
if (StateLabel(e->change, colour) && e->change != model::Action::Delete) if (StateLabel(e->change, colour) && e->change != model::Action::Delete)
facts += e->change == model::Action::Add ? " new here" : " changed here"; facts += e->change == model::Action::Add ? " new here" : " changed here";
if (!e->lock.empty()) }
facts += " locked by " + e->lock; if (e && !e->lock.empty()) {
const model::Lock *lock = repo.FindLock(e->path);
std::string since = lock && lock->locked_at_ms ? " since " + model::Date(lock->locked_at_ms) : "";
facts += " locked by " + (e->lock_mine ? std::string("you") : e->lock) + since;
} }
theme::TextColoured(theme::kMuted, facts.c_str()); theme::TextColoured(theme::kMuted, facts.c_str());
if (e && !e->dir && e->change != model::Action::Add) { if (e && !e->dir && e->change != model::Action::Add) {
@ -749,19 +905,33 @@ void Explorer::DrawChanges(const model::Workspace &ws, model::Repo &repo, Explor
if (theme::Button("RESCAN", !busy)) if (theme::Button("RESCAN", !busy))
host.LoadChanges(); host.LoadChanges();
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
int checked = 0; // Files someone else has locked stay out of the submit whatever is chosen.
for (const auto &c : repo.changes) int checked = 0, blocked = 0;
checked += !repo.unchecked.count(c.path); std::vector<std::string> to_lock;
for (const auto &c : repo.changes) {
bool on = !repo.unchecked.count(c.path) && !c.Blocked();
checked += on;
blocked += c.Blocked();
if (on && c.lock.empty() && c.action != model::Action::Delete)
to_lock.push_back(c.path);
}
if (theme::Button("ALL", !repo.changes.empty())) if (theme::Button("ALL", !repo.changes.empty()))
repo.unchecked.clear(); repo.unchecked.clear();
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
if (theme::Button("NONE", !repo.changes.empty())) if (theme::Button("NONE", !repo.changes.empty()))
for (const auto &c : repo.changes) for (const auto &c : repo.changes)
repo.unchecked.insert(c.path); repo.unchecked.insert(c.path);
ImGui::SameLine(0, 12);
if (theme::Button("LOCK", connected && !busy && ws.signed_in && !to_lock.empty()))
host.Lock(to_lock);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("lock the chosen files nobody holds yet");
ImGui::SameLine(0, 16); ImGui::SameLine(0, 16);
ImGui::AlignTextToFramePadding(); ImGui::AlignTextToFramePadding();
std::string count = std::to_string(checked) + "/" + std::to_string(repo.changes.size()) + " chosen"; std::string count = std::to_string(checked) + "/" + std::to_string(repo.changes.size()) + " chosen";
theme::TextColoured(theme::kMuted, count.c_str()); if (blocked)
count += ", " + std::to_string(blocked) + " locked by others";
theme::TextColoured(blocked ? theme::kSpark : theme::kMuted, count.c_str());
Gap(6); Gap(6);
const float compose_h = 128; const float compose_h = 128;
@ -775,24 +945,30 @@ void Explorer::DrawChanges(const model::Workspace &ws, model::Repo &repo, Explor
Note(ws.ahead ? "nothing changed here; unpushed revisions remain" : "nothing changed here"); Note(ws.ahead ? "nothing changed here; unpushed revisions remain" : "nothing changed here");
for (const auto &c : repo.changes) { for (const auto &c : repo.changes) {
ImGui::PushID(c.path.c_str()); ImGui::PushID(c.path.c_str());
bool on = !repo.unchecked.count(c.path); bool on = !repo.unchecked.count(c.path) && !c.Blocked();
if (theme::Row("change", false, kRowH)) { if (theme::Row("change", false, kRowH) && !c.Blocked()) {
if (on) if (on)
repo.unchecked.insert(c.path); repo.unchecked.insert(c.path);
else else
repo.unchecked.erase(c.path); repo.unchecked.erase(c.path);
on = !on; on = !on;
} }
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) bool hovered = ImGui::IsItemHovered();
if (hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
GoToFile(c.path); GoToFile(c.path);
if (hovered && c.Blocked())
ImGui::SetTooltip("locked by %s; SUBMIT leaves it out until the lock is released", c.lock.c_str());
ImVec2 p = ImGui::GetItemRectMin(); ImVec2 p = ImGui::GetItemRectMin();
// A pixel checkbox: an inset square, filled when chosen. PixelCheck({p.x + 8, p.y + 4}, on, !c.Blocked());
Box({p.x + 8, p.y + 4}, {p.x + 20, p.y + 16}, theme::kMuted); float text_right = p.x + width - 90;
Box({p.x + 9, p.y + 5}, {p.x + 19, p.y + 15}, theme::kInk); if (!c.lock.empty()) {
if (on) std::string tag = c.lock_mine ? "LOCK" : "LOCKED BY " + c.lock;
Box({p.x + 11, p.y + 7}, {p.x + 17, p.y + 13}, theme::kForge); float tag_x = std::floor(p.x + width - 90 - theme::TagWidth(tag.c_str()));
theme::TagAt({tag_x, p.y + 2}, tag.c_str(), c.lock_mine ? theme::kBlue : theme::kRed);
text_right = tag_x - 10;
}
std::string text = c.from.empty() ? c.path : c.from + " -> " + c.path; std::string text = c.from.empty() ? c.path : c.from + " -> " + c.path;
theme::TextAt({p.x + 30, p.y + 2}, on ? theme::kPaper : theme::kMuted, text.c_str(), p.x + width - 90); theme::TextAt({p.x + 30, p.y + 2}, on ? theme::kPaper : theme::kMuted, text.c_str(), text_right);
ImU32 colour = 0; ImU32 colour = 0;
if (const char *label = StateLabel(c.action, colour)) if (const char *label = StateLabel(c.action, colour))
theme::TagAt({p.x + width - 80, p.y + 2}, label, colour); theme::TagAt({p.x + width - 80, p.y + 2}, label, colour);
@ -804,23 +980,83 @@ void Explorer::DrawChanges(const model::Workspace &ws, model::Repo &repo, Explor
Gap(8); Gap(8);
theme::TextColoured(theme::kMuted, "MESSAGE"); theme::TextColoured(theme::kMuted, "MESSAGE");
float button_w = theme::ButtonWidth("SUBMIT"); float column_w = std::max(theme::ButtonWidth("SUBMIT"), CheckBoxWidth("KEEP LOCKS"));
ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk); ImGui::PushStyleColor(ImGuiCol_FrameBg, theme::kInk);
ImGui::InputTextMultiline("##message", message_, sizeof message_, ImGui::InputTextMultiline("##message", message_, sizeof message_,
{ImGui::GetContentRegionAvail().x - button_w - 12, compose_h - 32}); {ImGui::GetContentRegionAvail().x - column_w - 12, compose_h - 32});
ImGui::PopStyleColor(); ImGui::PopStyleColor();
ImGui::SameLine(0, 12); ImGui::SameLine(0, 12);
const ImVec2 column = ImGui::GetCursorScreenPos();
bool has_message = message_[0] != 0; bool has_message = message_[0] != 0;
bool can_submit = connected && !busy && ws.signed_in && checked > 0 && has_message; bool can_submit = connected && !busy && ws.signed_in && checked > 0 && has_message;
bool can_push = connected && !busy && ws.signed_in && repo.changes.empty() && ws.ahead; bool can_push = connected && !busy && ws.signed_in && repo.changes.empty() && ws.ahead;
if (can_push) { if (can_push) {
if (theme::Button("PUSH", true, true)) if (theme::Button("PUSH", true, true))
host.Submit("", {}); host.Submit("", {}, false);
} else if (theme::Button("SUBMIT", can_submit, true)) { } else if (theme::Button("SUBMIT", can_submit, true)) {
std::vector<std::string> paths; std::vector<std::string> paths;
for (const auto &c : repo.changes) for (const auto &c : repo.changes)
if (!repo.unchecked.count(c.path)) if (!repo.unchecked.count(c.path) && !c.Blocked())
paths.push_back(c.path); paths.push_back(c.path);
host.Submit(message_, paths); host.Submit(message_, paths, keep_locks_);
} }
ImGui::SetCursorScreenPos({column.x, column.y + ImGui::GetFrameHeight() + 10});
CheckBox("KEEP LOCKS", keep_locks_, !can_push);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("hold your locks on the submitted files; otherwise SUBMIT releases them");
}
// ---- Locks
void Explorer::DrawLocks(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected) {
if (repo.locks_state == model::Load::None)
host.LoadLocks();
std::vector<std::string> mine, theirs;
for (const auto &l : repo.locks)
if (lock_marked_.count(l.path))
(l.mine ? mine : theirs).push_back(l.path);
bool can = connected && ws.signed_in && ws.state != "syncing";
if (theme::Button("REFRESH", repo.locks_state != model::Load::Loading))
host.LoadLocks();
ImGui::SameLine(0, 12);
if (theme::Button("UNLOCK", can && !mine.empty()))
host.Unlock(mine, false);
ImGui::SameLine(0, 12);
if (theme::Button("FORCE UNLOCK", can && !theirs.empty()))
host.Unlock(theirs, true);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("release other people's locks; the server allows it to repository admins");
ImGui::SameLine(0, 16);
ImGui::AlignTextToFramePadding();
std::string branch = repo.locks_branch.empty() ? ws.branch : repo.locks_branch;
size_t yours = std::count_if(repo.locks.begin(), repo.locks.end(), [](const model::Lock &l) { return l.mine; });
std::string count = std::to_string(repo.locks.size()) + " on " + branch + ", " + std::to_string(yours) + " yours";
theme::TextColoured(theme::kMuted, count.c_str());
Gap(6);
BeginList("locks", {0, 0});
float width = ImGui::GetContentRegionAvail().x;
const float owner_x = std::floor(width * 0.55f), since_x = width - 140;
HeaderRow({{30, "FILE"}, {owner_x, "HELD BY"}, {since_x, "SINCE"}});
if (repo.locks_state == model::Load::Failed)
Note(repo.locks_error.c_str(), theme::kRed);
else if (repo.locks.empty())
Note(repo.locks_state == model::Load::Ready ? "nobody holds a lock on this branch" : "reading");
for (const auto &l : repo.locks) {
ImGui::PushID(l.path.c_str());
if (theme::Row("lock", lock_marked_.count(l.path) > 0, kRowH))
Choose(lock_marked_, l.path);
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
GoToFile(l.path);
ImVec2 p = ImGui::GetItemRectMin();
ImU32 colour = l.mine ? theme::kBlue : theme::kRed;
Box({p.x + 10, p.y + 6}, {p.x + 18, p.y + 14}, colour);
theme::TextAt({p.x + 30, p.y + 2}, theme::kPaper, l.path.c_str(), p.x + owner_x - 12);
theme::TextAt({p.x + owner_x, p.y + 2}, l.mine ? theme::kBlue : theme::kPaper,
l.mine ? "you" : l.owner.c_str(), p.x + since_x - 12);
std::string since = model::Date(l.locked_at_ms);
theme::TextAt({p.x + since_x, p.y + 2}, theme::kMuted, since.c_str());
ImGui::PopID();
}
EndList();
} }

View File

@ -17,15 +17,22 @@ class ExplorerHost {
virtual void LoadRevision(const std::string &signature) = 0; virtual void LoadRevision(const std::string &signature) = 0;
virtual void LoadFileHistory(const std::string &path) = 0; virtual void LoadFileHistory(const std::string &path) = 0;
virtual void LoadChanges() = 0; virtual void LoadChanges() = 0;
virtual void LoadLocks() = 0;
virtual void Refresh() = 0; virtual void Refresh() = 0;
virtual void Sync() = 0; virtual void Sync() = 0;
virtual void Submit(const std::string &message, const std::vector<std::string> &paths) = 0; virtual void Submit(const std::string &message, const std::vector<std::string> &paths, bool keep_locks) = 0;
virtual void SignIn() = 0; virtual void SignIn() = 0;
virtual void Lock(const std::vector<std::string> &paths) = 0;
// `force` releases other people's locks too, which the server allows repository admins.
virtual void Unlock(const std::vector<std::string> &paths, bool force) = 0;
// autosync: "off", "interval" or "on_change".
virtual void SetAutosync(const std::string &autosync, uint64_t interval_s) = 0;
virtual void SetLockOnEdit(bool on) = 0;
}; };
class Explorer { class Explorer {
public: public:
// "files", "graph", "tree" or "changes". // "files", "graph", "tree", "changes" or "locks".
void SetTab(const std::string &name); void SetTab(const std::string &name);
// The sidebar's branch list for `repo`. // The sidebar's branch list for `repo`.
void DrawBranches(const model::Repo &repo); void DrawBranches(const model::Repo &repo);
@ -35,7 +42,7 @@ class Explorer {
void ClearMessage() { message_[0] = 0; } void ClearMessage() { message_[0] = 0; }
private: private:
enum class Tab { Files, Graph, Tree, Changes }; enum class Tab { Files, Graph, Tree, Changes, Locks };
// One row of the revision graph: which lanes carry lines in and out, where the node sits. // One row of the revision graph: which lanes carry lines in and out, where the node sits.
struct GraphRow { struct GraphRow {
@ -47,7 +54,7 @@ class Explorer {
void Layout(const model::Repo &repo); void Layout(const model::Repo &repo);
void DrawBar(const model::Workspace &ws, const model::Repo &repo, ExplorerHost &host, bool connected); void DrawBar(const model::Workspace &ws, const model::Repo &repo, ExplorerHost &host, bool connected);
void DrawFiles(model::Repo &repo, ExplorerHost &host); void DrawFiles(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host);
void DrawBreadcrumbs(const model::Workspace &ws); void DrawBreadcrumbs(const model::Workspace &ws);
void DrawDirTree(model::Repo &repo, ExplorerHost &host, const std::string &dir, const std::string &name, int depth); void DrawDirTree(model::Repo &repo, ExplorerHost &host, const std::string &dir, const std::string &name, int depth);
void DrawFileList(model::Repo &repo, ExplorerHost &host); void DrawFileList(model::Repo &repo, ExplorerHost &host);
@ -56,6 +63,8 @@ class Explorer {
void DrawRevisionDetails(model::Repo &repo, ExplorerHost &host); void DrawRevisionDetails(model::Repo &repo, ExplorerHost &host);
void DrawTree(model::Repo &repo, ExplorerHost &host); void DrawTree(model::Repo &repo, ExplorerHost &host);
void DrawChanges(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected); void DrawChanges(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected);
void DrawLocks(const model::Workspace &ws, model::Repo &repo, ExplorerHost &host, bool connected);
void DrawAutosync(const model::Workspace &ws, ExplorerHost &host, bool connected);
void DrawRevisionLine(const model::Repo &repo, const model::Revision &rev, float x, float y, float right); void DrawRevisionLine(const model::Repo &repo, const model::Revision &rev, float x, float y, float right);
void DrawChangeRow(const model::Change &change, float indent); void DrawChangeRow(const model::Change &change, float indent);
void GoToFile(const std::string &path); void GoToFile(const std::string &path);
@ -73,5 +82,9 @@ class Explorer {
std::string selected_rev_; std::string selected_rev_;
bool scroll_to_rev_ = false; bool scroll_to_rev_ = false;
std::set<std::string> open_dirs_, open_branches_, open_revisions_; std::set<std::string> open_dirs_, open_branches_, open_revisions_;
std::set<std::string> marked_; // files chosen in the file list, for LOCK and UNLOCK
std::set<std::string> lock_marked_; // rows chosen in the LOCKS tab
bool keep_locks_ = false;
int interval_min_ = 5; // the autosync popup's minutes while it is open
char message_[2048] = {}; char message_[2048] = {};
}; };

View File

@ -13,7 +13,7 @@
// --config-from FILE with --test: the private service's desktop.toml; the test then // --config-from FILE with --test: the private service's desktop.toml; the test then
// syncs the first workspace and waits for it and its explorer data // syncs the first workspace and waits for it and its explorer data
// --screenshot FILE with --test: write the final frame as a PNG // --screenshot FILE with --test: write the final frame as a PNG
// --tab files|graph|tree|changes the explorer tab to open on // --tab files|graph|tree|changes|locks the explorer tab to open on
// forge-desktop --licenses print the licences of what is compiled in // forge-desktop --licenses print the licences of what is compiled in
#define UHDK_ENABLE_OPENGL #define UHDK_ENABLE_OPENGL
#include "uhdk.h" #include "uhdk.h"
@ -141,10 +141,15 @@ class App : public ExplorerHost {
void LoadRevision(const std::string &signature) override; void LoadRevision(const std::string &signature) override;
void LoadFileHistory(const std::string &path) override; void LoadFileHistory(const std::string &path) override;
void LoadChanges() override; void LoadChanges() override;
void LoadLocks() override;
void Refresh() override; void Refresh() override;
void Sync() override; void Sync() override;
void Submit(const std::string &message, const std::vector<std::string> &paths) override; void Submit(const std::string &message, const std::vector<std::string> &paths, bool keep_locks) override;
void SignIn() override; void SignIn() override;
void Lock(const std::vector<std::string> &paths) override;
void Unlock(const std::vector<std::string> &paths, bool force) override;
void SetAutosync(const std::string &autosync, uint64_t interval_s) override;
void SetLockOnEdit(bool on) override;
private: private:
bool Initialize(); bool Initialize();
@ -162,6 +167,8 @@ class App : public ExplorerHost {
void DrawSidebar(); void DrawSidebar();
void DrawAdd(); void DrawAdd();
void DrawFooter(); void DrawFooter();
void DrawNotices();
void Settings(const std::string &fields);
const model::Workspace *SelectedWorkspace() const; const model::Workspace *SelectedWorkspace() const;
model::Repo &RepoOf(const std::string &id) { return repos_[id]; } model::Repo &RepoOf(const std::string &id) { return repos_[id]; }
void Call(const std::string &method, const std::string &params, Handler handler = nullptr); void Call(const std::string &method, const std::string &params, Handler handler = nullptr);
@ -194,6 +201,7 @@ class App : public ExplorerHost {
std::string liblore_, liblore_error_; std::string liblore_, liblore_error_;
std::vector<std::string> accounts_; // "alice at localhost:18081" std::vector<std::string> accounts_; // "alice at localhost:18081"
std::string error_; std::string error_;
std::vector<std::string> notices_; // from the service, newest last
std::map<uint64_t, Handler> pending_; std::map<uint64_t, Handler> pending_;
std::vector<model::Workspace> workspaces_; std::vector<model::Workspace> workspaces_;
std::map<std::string, model::Repo> repos_; std::map<std::string, model::Repo> repos_;
@ -298,6 +306,12 @@ void App::UpdateTray() {
syncing += w.state == "syncing"; syncing += w.state == "syncing";
tooltip += syncing ? "syncing " + std::to_string(syncing) + "/" + std::to_string(workspaces_.size()) tooltip += syncing ? "syncing " + std::to_string(syncing) + "/" + std::to_string(workspaces_.size())
: std::to_string(workspaces_.size()) + " workspaces"; : std::to_string(workspaces_.size()) + " workspaces";
// Warnings and notices need the user; say the newest.
for (const auto &w : workspaces_)
if (!w.warning.empty())
tooltip += "\n" + w.name + ": " + w.warning;
if (!notices_.empty())
tooltip += "\n" + notices_.back();
} }
bool sync_enabled = Connected() && !workspaces_.empty(); bool sync_enabled = Connected() && !workspaces_.empty();
if (tray_ && tooltip == tray_tooltip_ && sync_enabled == tray_sync_enabled_) if (tray_ && tooltip == tray_tooltip_ && sync_enabled == tray_sync_enabled_)
@ -473,6 +487,85 @@ void App::LoadChanges() {
}); });
} }
void App::LoadLocks() {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
std::string id = w->id;
model::Repo &repo = RepoOf(id);
repo.locks_state = model::Load::Loading;
unsigned generation = repo.generation;
Call("locks", "{\"workspace\":" + Q(id) + "}", [this, id, generation](const json::Value &result, const json::Value &error) {
model::Repo &repo = RepoOf(id);
if (repo.generation != generation) {
if (repo.locks_state == model::Load::Loading)
repo.locks_state = model::Load::None;
return;
}
if (error.is_object()) {
repo.locks_state = model::Load::Failed;
repo.locks_error = error["message"].str();
return;
}
repo.locks = model::ParseLocks(result["locks"]);
repo.locks_branch = result["branch"].str();
repo.locks_state = model::Load::Ready;
});
}
static std::string List(const std::vector<std::string> &paths) {
std::string list = "[";
for (size_t i = 0; i < paths.size(); ++i)
list += (i ? "," : "") + json::Quote(paths[i]);
return list + "]";
}
void App::Lock(const std::vector<std::string> &paths) {
const model::Workspace *w = SelectedWorkspace();
if (!w || paths.empty())
return;
std::string id = w->id;
Call("lock", "{\"workspace\":" + Q(id) + ",\"paths\":" + List(paths) + "}",
[this, id](const json::Value &, const json::Value &error) {
if (error.is_object())
error_ = error["message"].str();
RepoOf(id).ResetLocks();
});
}
void App::Unlock(const std::vector<std::string> &paths, bool force) {
const model::Workspace *w = SelectedWorkspace();
if (!w || paths.empty())
return;
std::string id = w->id;
Call("unlock",
"{\"workspace\":" + Q(id) + ",\"paths\":" + List(paths) + ",\"force\":" + (force ? "true" : "false") + "}",
[this, id](const json::Value &, const json::Value &error) {
if (error.is_object())
error_ = error["message"].str();
RepoOf(id).ResetLocks();
});
}
void App::Settings(const std::string &fields) {
const model::Workspace *w = SelectedWorkspace();
if (!w)
return;
Call("workspace_settings", "{\"workspace\":" + Q(w->id) + "," + fields + "}",
[this](const json::Value &, const json::Value &error) {
if (error.is_object())
error_ = error["message"].str();
});
}
void App::SetAutosync(const std::string &autosync, uint64_t interval_s) {
Settings("\"autosync\":" + Q(autosync) + ",\"interval_s\":" + std::to_string(interval_s));
}
void App::SetLockOnEdit(bool on) {
Settings(std::string("\"lock_on_edit\":") + (on ? "true" : "false"));
}
void App::Refresh() { void App::Refresh() {
const model::Workspace *w = SelectedWorkspace(); const model::Workspace *w = SelectedWorkspace();
if (!w) if (!w)
@ -486,15 +579,16 @@ void App::Sync() {
Call("sync_now", "{\"workspace\":" + Q(w->id) + "}"); Call("sync_now", "{\"workspace\":" + Q(w->id) + "}");
} }
void App::Submit(const std::string &message, const std::vector<std::string> &paths) { void App::Submit(const std::string &message, const std::vector<std::string> &paths, bool keep_locks) {
const model::Workspace *w = SelectedWorkspace(); const model::Workspace *w = SelectedWorkspace();
if (!w) if (!w)
return; return;
std::string list = "["; Call("submit", "{\"workspace\":" + Q(w->id) + ",\"message\":" + Q(message) + ",\"paths\":" + List(paths) +
for (size_t i = 0; i < paths.size(); ++i) ",\"keep_locks\":" + (keep_locks ? "true" : "false") + "}",
list += (i ? "," : "") + Q(paths[i]); [this](const json::Value &, const json::Value &error) {
list += "]"; if (error.is_object())
Call("submit", "{\"workspace\":" + Q(w->id) + ",\"message\":" + Q(message) + ",\"paths\":" + list + "}"); error_ = error["message"].str();
});
} }
void App::SignIn() { void App::SignIn() {
@ -658,14 +752,25 @@ void App::HandleMessage(const json::Value &message) {
} }
if (done || w.activity.phase == "failed") if (done || w.activity.phase == "failed")
RepoOf(w.id).Reset(); RepoOf(w.id).Reset();
// The test's sync only brings the workspace up to date; one Lore refuses (local
// edits overlapping remote ones, say) leaves a state still worth drawing.
if (test_ && w.activity.kind == "sync" && (done || w.activity.phase == "failed")) { if (test_ && w.activity.kind == "sync" && (done || w.activity.phase == "failed")) {
test_sync_done_ = true; test_sync_done_ = true;
if (!done) { if (!done)
std::fprintf(stderr, "forge-desktop: --test: sync failed: %s\n", w.activity.message.c_str()); std::fprintf(stderr, "forge-desktop: --test: sync failed, going on: %s\n",
test_failed_ = true; w.activity.message.c_str());
}
} }
} }
} else if (method == "locks") {
RepoOf(params["workspace"].str()).ResetLocks();
} else if (method == "notice") {
std::string where;
for (const auto &w : workspaces_)
if (w.id == params["workspace"].str())
where = w.name + ": ";
notices_.push_back(where + params["message"].str());
if (notices_.size() > 4)
notices_.erase(notices_.begin());
} else if (method == "login") { } else if (method == "login") {
login_.remote = params["remote"].str(); login_.remote = params["remote"].str();
login_.phase = params["phase"].str(); login_.phase = params["phase"].str();
@ -980,6 +1085,24 @@ void App::DrawAdd() {
ImGui::PopStyleColor(); ImGui::PopStyleColor();
} }
// Notices from the service, such as someone locking a file edited here, until dismissed.
void App::DrawNotices() {
for (size_t i = 0; i < notices_.size(); ++i) {
ImGui::PushID(int(i));
bool dismiss = theme::Button("X");
ImGui::SameLine(0, 12);
ImGui::AlignTextToFramePadding();
ImGui::PushStyleColor(ImGuiCol_Text, theme::kSpark);
ImGui::TextWrapped("%s", notices_[i].c_str());
ImGui::PopStyleColor();
ImGui::PopID();
if (dismiss) {
notices_.erase(notices_.begin() + long(i));
break;
}
}
}
void App::DrawFooter() { void App::DrawFooter() {
theme::Rule(); theme::Rule();
std::vector<const char *> buttons; std::vector<const char *> buttons;
@ -1053,6 +1176,7 @@ void App::Draw(const uhdk_window_metrics &metrics) {
ImGui::TextWrapped("%s", error_.c_str()); ImGui::TextWrapped("%s", error_.c_str());
ImGui::PopStyleColor(); ImGui::PopStyleColor();
} }
DrawNotices();
// The footer: a rule, then one row of buttons with their shadow. // The footer: a rule, then one row of buttons with their shadow.
const ImGuiStyle &style = ImGui::GetStyle(); const ImGuiStyle &style = ImGui::GetStyle();
@ -1113,6 +1237,8 @@ void App::TestStep() {
ready = ready && repo.changes_state == model::Load::Ready; ready = ready && repo.changes_state == model::Load::Ready;
} else if (test_tab_ == "graph" || test_tab_ == "tree") { } else if (test_tab_ == "graph" || test_tab_ == "tree") {
ready = ready && repo.revisions_loading.empty(); ready = ready && repo.revisions_loading.empty();
} else if (test_tab_ == "locks") {
ready = ready && repo.locks_state == model::Load::Ready;
} }
} }
if (!ready) { if (!ready) {
@ -1247,7 +1373,7 @@ int main(int argc, char **argv) {
std::fprintf(stderr, "Usage: forge-desktop [--hidden] [--service PATH] [--liblore=PATH]\n" std::fprintf(stderr, "Usage: forge-desktop [--hidden] [--service PATH] [--liblore=PATH]\n"
" forge-desktop --licenses\n" " forge-desktop --licenses\n"
" forge-desktop --test [--service PATH] [--liblore=PATH] [--config-from FILE]\n" " forge-desktop --test [--service PATH] [--liblore=PATH] [--config-from FILE]\n"
" [--screenshot FILE] [--tab files|graph|tree|changes]\n"); " [--screenshot FILE] [--tab files|graph|tree|changes|locks]\n");
return 2; return 2;
} }
} }

View File

@ -33,6 +33,27 @@ void Repo::Reset() {
file_history_loading.clear(); file_history_loading.clear();
changes_state = Load::None; changes_state = Load::None;
changes.clear(); changes.clear();
locks_state = Load::None;
locks_error.clear();
locks.clear();
}
void Repo::ResetLocks() {
// Keeps the generation, so answers already on their way to other views still land.
dirs.clear();
dir_state.clear();
dir_errors.clear();
if (changes_state != Load::Loading)
changes_state = Load::None;
if (locks_state != Load::Loading)
locks_state = Load::None;
}
const Lock *Repo::FindLock(const std::string &path) const {
for (const auto &l : locks)
if (l.path == path)
return &l;
return nullptr;
} }
const Revision *Repo::FindRevision(const std::string &signature) const { const Revision *Repo::FindRevision(const std::string &signature) const {
@ -87,6 +108,9 @@ std::vector<Workspace> ParseWorkspaces(const json::Value &list, const std::vecto
w.behind = item["behind"].boolean(); w.behind = item["behind"].boolean();
w.online = item["online"].boolean(); w.online = item["online"].boolean();
w.signed_in = item["signed_in"].boolean(); w.signed_in = item["signed_in"].boolean();
w.warning = item["warning"].str();
w.interval_s = uint64_t(item["interval_s"].num(300));
w.lock_on_edit = item["lock_on_edit"].boolean();
for (const auto &old : previous) for (const auto &old : previous)
if (old.id == w.id) if (old.id == w.id)
w.activity = old.activity; w.activity = old.activity;
@ -104,6 +128,8 @@ std::vector<Change> ParseChanges(const json::Value &list) {
c.action = ParseAction(item["action"].str()); c.action = ParseAction(item["action"].str());
c.staged = item["staged"].boolean(); c.staged = item["staged"].boolean();
c.conflict = item["conflict"].boolean(); c.conflict = item["conflict"].boolean();
c.lock = item["lock"].str();
c.lock_mine = item["lock_mine"].boolean();
out.push_back(std::move(c)); out.push_back(std::move(c));
} }
return out; return out;
@ -158,6 +184,20 @@ std::vector<FileEntry> ParseEntries(const json::Value &list) {
return out; return out;
} }
std::vector<Lock> ParseLocks(const json::Value &list) {
std::vector<Lock> out;
for (const auto &item : list.items()) {
Lock l;
l.path = item["path"].str();
l.owner = item["owner"].str();
l.owner_id = item["owner_id"].str();
l.mine = item["mine"].boolean();
l.locked_at_ms = uint64_t(item["locked_at_ms"].num());
out.push_back(std::move(l));
}
return out;
}
std::string Short(const std::string &signature) { std::string Short(const std::string &signature) {
return signature.substr(0, 7); return signature.substr(0, 7);
} }

View File

@ -24,15 +24,25 @@ struct Activity {
struct Workspace { struct Workspace {
std::string id, name, path, remote, state, autosync; std::string id, name, path, remote, state, autosync;
std::string branch, signature, error; std::string branch, signature, error;
uint64_t revision = 0, changes = 0; std::string warning; // why autosync is holding back
bool ahead = false, behind = false, online = false, signed_in = false; uint64_t revision = 0, changes = 0, interval_s = 300;
bool ahead = false, behind = false, online = false, signed_in = false, lock_on_edit = false;
Activity activity; Activity activity;
}; };
struct Change { struct Change {
std::string path, from; std::string path, from;
std::string lock; // who holds the file's lock; empty when nobody does
Action action = Action::Modify; Action action = Action::Modify;
bool staged = false, conflict = false; bool staged = false, conflict = false, lock_mine = false;
// Locked by someone else: SUBMIT leaves it out.
bool Blocked() const { return !lock.empty() && !lock_mine; }
};
struct Lock {
std::string path, owner, owner_id;
bool mine = false;
uint64_t locked_at_ms = 0;
}; };
struct Branch { struct Branch {
@ -81,7 +91,14 @@ struct Repo {
std::vector<Change> changes; std::vector<Change> changes;
std::set<std::string> unchecked; // changes left out of the next submit std::set<std::string> unchecked; // changes left out of the next submit
Load locks_state = Load::None;
std::string locks_branch, locks_error;
std::vector<Lock> locks; // yours first
void Reset(); // everything but revision_changes void Reset(); // everything but revision_changes
// After someone locks or unlocks: what shows locks is read again.
void ResetLocks();
const Lock *FindLock(const std::string &path) const;
const Revision *FindRevision(const std::string &signature) const; const Revision *FindRevision(const std::string &signature) const;
const Branch *FindBranch(const std::string &id) const; const Branch *FindBranch(const std::string &id) const;
const Branch *CurrentBranch() const; const Branch *CurrentBranch() const;
@ -93,6 +110,7 @@ std::vector<Change> ParseChanges(const json::Value &list);
std::vector<Branch> ParseBranches(const json::Value &list); std::vector<Branch> ParseBranches(const json::Value &list);
std::vector<Revision> ParseRevisions(const json::Value &list); std::vector<Revision> ParseRevisions(const json::Value &list);
std::vector<FileEntry> ParseEntries(const json::Value &list); std::vector<FileEntry> ParseEntries(const json::Value &list);
std::vector<Lock> ParseLocks(const json::Value &list);
// "a3f9c21": the first seven hex digits of a signature. // "a3f9c21": the first seven hex digits of a signature.
std::string Short(const std::string &signature); std::string Short(const std::string &signature);

View File

@ -21,7 +21,7 @@
class ServiceClient { class ServiceClient {
public: public:
static constexpr int kProtocolVersion = 2; static constexpr int kProtocolVersion = 3;
enum class State { Connecting, StartingService, Connected, Unavailable }; enum class State { Connecting, StartingService, Connected, Unavailable };

View File

@ -4,7 +4,9 @@
//! //!
//! Operations: status, scan, branches, history, info <rev>, diff <from> <to>, locks, files <path>, //! Operations: status, scan, branches, history, info <rev>, diff <from> <to>, locks, files <path>,
//! repos <remote>, users <id>, logins, clone <url>, sync, login <remote>, stage <path>, //! repos <remote>, users <id>, logins, clone <url>, sync, login <remote>, stage <path>,
//! commit <message>, push. //! commit <message>, push, lock <path> [branch], unlock <path> [branch] [owner id],
//! lockstatus <path> [branch], watch (notifications until killed), watchfor <seconds>
//! (subscribes, then unsubscribes from another thread).
use lore_sys::Globals; use lore_sys::Globals;
use lore_sys::Lore; use lore_sys::Lore;
@ -17,6 +19,7 @@ fn main() {
let globals = Globals { repository_path: args.get(1).cloned().unwrap_or_default(), ..Globals::default() }; let globals = Globals { repository_path: args.get(1).cloned().unwrap_or_default(), ..Globals::default() };
let a = args.get(2).cloned().unwrap_or_default(); let a = args.get(2).cloned().unwrap_or_default();
let b = args.get(3).cloned().unwrap_or_default(); let b = args.get(3).cloned().unwrap_or_default();
let c = args.get(4).cloned().unwrap_or_default();
let print = |event| println!("{event:?}"); let print = |event| println!("{event:?}");
let result = match op { let result = match op {
"status" => lore.repository_status(&globals, false, print), "status" => lore.repository_status(&globals, false, print),
@ -35,6 +38,23 @@ fn main() {
"stage" => lore.file_stage(&globals, std::slice::from_ref(&a), print), "stage" => lore.file_stage(&globals, std::slice::from_ref(&a), print),
"commit" => lore.revision_commit(&globals, &a, print), "commit" => lore.revision_commit(&globals, &a, print),
"push" => lore.branch_push(&globals, print), "push" => lore.branch_push(&globals, print),
"lock" => lore.lock_file_acquire(&globals, std::slice::from_ref(&a), &b, print),
"unlock" => lore.lock_file_release(&globals, std::slice::from_ref(&a), &b, "", &c, print),
"lockstatus" => lore.lock_file_status(&globals, std::slice::from_ref(&a), &b, print),
"watch" => lore.notification_subscribe(&globals, |event| {
println!("{event:?}");
use std::io::Write;
std::io::stdout().flush().unwrap();
}),
"watchfor" => std::thread::scope(|scope| {
let watcher = scope.spawn(|| lore.notification_subscribe(&globals, |event| println!("watch: {event:?}")));
std::thread::sleep(std::time::Duration::from_secs(a.parse().unwrap()));
println!("unsubscribe: {:?}", lore.notification_unsubscribe(&globals, print));
let started = std::time::Instant::now();
let ended = watcher.join().unwrap();
println!("subscribe ended after {:?}: {ended:?}", started.elapsed());
Ok(())
}),
"login" => lore.auth_login_interactive(&globals, &a, true, print), "login" => lore.auth_login_interactive(&globals, &a, true, print),
other => panic!("unknown operation {other}"), other => panic!("unknown operation {other}"),
}; };

View File

@ -136,6 +136,23 @@ pub enum Event {
DiffFile { path: String, action: Action, file: bool, from: String }, DiffFile { path: String, action: Action, file: bool, from: String },
FileHistory { signature: String, number: u64, action: Action, size: u64, from: String }, FileHistory { signature: String, number: u64, action: Action, size: u64, from: String },
Lock { branch: String, path: String, owner: String, locked_at: u64 }, Lock { branch: String, path: String, owner: String, locked_at: u64 },
/// The acquire entries that follow were newly locked, or `ignored` (already ours).
LockAcquireBegin { ignored: bool },
LockAcquired { path: String },
/// The release entries that follow; `not_found` when there was no such lock.
LockReleaseBegin { not_found: bool },
LockReleased { path: String },
/// A path's lock holder (empty: unlocked).
LockStatus { path: String, owner: String, locked_at: u64 },
/// A notification subscription is live for `repository`.
Subscribed { repository: String },
Unsubscribed { repository: String },
BranchCreated { branch: String },
BranchDeleted { branch: String },
/// Someone pushed `signature` to `branch`.
BranchPushed { branch: String, signature: String, number: u64, user_id: String },
ResourcesLocked { branch: String, user_id: String, paths: Vec<String> },
ResourcesUnlocked { branch: String, user_id: String, paths: Vec<String> },
Repository { id: String, name: String }, Repository { id: String, name: String },
/// A repository configuration value. /// A repository configuration value.
Config { key: String, value: String }, Config { key: String, value: String },
@ -378,6 +395,56 @@ impl Lore {
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_query_async(g, &args, cb) }, on)) with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_query_async(g, &args, cb) }, on))
} }
/// Locks `paths` on `branch`, as [`Event::LockAcquireBegin`] and [`Event::LockAcquired`].
pub fn lock_file_acquire(&self, globals: &Globals, paths: &[String], branch: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let paths = strings(paths);
let mut args = b::lore_lock_file_acquire_args_t::default();
args.paths = array(&paths);
args.branch = s(branch);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_acquire_async(g, &args, cb) }, on))
}
/// Releases locks on `paths`, as [`Event::LockReleaseBegin`] and [`Event::LockReleased`].
/// `owner` and `owner_id` name whose locks; empty for the caller's own.
pub fn lock_file_release(
&self,
globals: &Globals,
paths: &[String],
branch: &str,
owner: &str,
owner_id: &str,
on: impl FnMut(Event),
) -> Result<(), Error> {
let paths = strings(paths);
let mut args = b::lore_lock_file_release_args_t::default();
args.paths = array(&paths);
args.branch = s(branch);
args.owner = s(owner);
args.owner_id = s(owner_id);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_release_async(g, &args, cb) }, on))
}
/// Who holds the locks on `paths`, as [`Event::LockStatus`].
pub fn lock_file_status(&self, globals: &Globals, paths: &[String], branch: &str, on: impl FnMut(Event)) -> Result<(), Error> {
let paths = strings(paths);
let mut args = b::lore_lock_file_status_args_t::default();
args.paths = array(&paths);
args.branch = s(branch);
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_lock_file_status_async(g, &args, cb) }, on))
}
/// Subscribes to the working copy's repository's notifications. Events arrive until the
/// subscription ends.
pub fn notification_subscribe(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_notification_subscribe_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_notification_subscribe_async(g, &args, cb) }, on))
}
pub fn notification_unsubscribe(&self, globals: &Globals, on: impl FnMut(Event)) -> Result<(), Error> {
let args = b::lore_notification_unsubscribe_args_t::default();
with_globals(globals, |g| self.call(|cb| unsafe { self.lib.lore_notification_unsubscribe_async(g, &args, cb) }, on))
}
/// The revisions that changed `path`, newest first, as [`Event::FileHistory`]. /// The revisions that changed `path`, newest first, as [`Event::FileHistory`].
pub fn file_history(&self, globals: &Globals, path: &str, length: u32, on: impl FnMut(Event)) -> Result<(), Error> { pub fn file_history(&self, globals: &Globals, path: &str, length: u32, on: impl FnMut(Event)) -> Result<(), Error> {
let mut args = b::lore_file_history_args_t::default(); let mut args = b::lore_file_history_args_t::default();
@ -608,6 +675,47 @@ unsafe fn decode(event: &b::lore_event_t) -> Event {
locked_at: e.locked_at, locked_at: e.locked_at,
} }
} }
b::LORE_EVENT_LOCK_FILE_ACQUIRE_BEGIN => {
Event::LockAcquireBegin { ignored: data.lock_file_acquire_begin.ignored != 0 }
}
b::LORE_EVENT_LOCK_FILE_ACQUIRE => Event::LockAcquired { path: text(&data.lock_file_acquire.path) },
b::LORE_EVENT_LOCK_FILE_RELEASE_BEGIN => {
Event::LockReleaseBegin { not_found: data.lock_file_release_begin.not_found != 0 }
}
b::LORE_EVENT_LOCK_FILE_RELEASE => Event::LockReleased { path: text(&data.lock_file_release.path) },
b::LORE_EVENT_LOCK_FILE_STATUS => {
let e = &data.lock_file_status;
Event::LockStatus { path: text(&e.path), owner: text(&e.owner), locked_at: e.locked_at }
}
b::LORE_EVENT_NOTIFICATION_SUBSCRIBED => {
Event::Subscribed { repository: hex(&data.notification_subscribed.repository.data) }
}
b::LORE_EVENT_NOTIFICATION_UNSUBSCRIBED => {
Event::Unsubscribed { repository: hex(&data.notification_unsubscribed.repository.data) }
}
b::LORE_EVENT_NOTIFICATION_BRANCH_CREATED => {
Event::BranchCreated { branch: hex(&data.notification_branch_created.branch.data) }
}
b::LORE_EVENT_NOTIFICATION_BRANCH_DELETED => {
Event::BranchDeleted { branch: hex(&data.notification_branch_deleted.branch.data) }
}
b::LORE_EVENT_NOTIFICATION_BRANCH_PUSHED => {
let e = &data.notification_branch_pushed;
Event::BranchPushed {
branch: hex(&e.branch.data),
signature: hex(&e.revision.data),
number: e.revision_number,
user_id: text(&e.user_id),
}
}
b::LORE_EVENT_NOTIFICATION_RESOURCE_LOCKED => {
let e = &data.notification_resource_locked;
Event::ResourcesLocked { branch: hex(&e.branch.data), user_id: text(&e.user_id), paths: texts(&e.paths) }
}
b::LORE_EVENT_NOTIFICATION_RESOURCE_UNLOCKED => {
let e = &data.notification_resource_unlocked;
Event::ResourcesUnlocked { branch: hex(&e.branch.data), user_id: text(&e.user_id), paths: texts(&e.paths) }
}
b::LORE_EVENT_REPOSITORY_LIST_ENTRY => { b::LORE_EVENT_REPOSITORY_LIST_ENTRY => {
let e = &data.repository_list_entry; let e = &data.repository_list_entry;
Event::Repository { id: hex(&e.id.data), name: text(&e.name) } Event::Repository { id: hex(&e.id.data), name: text(&e.name) }
@ -686,6 +794,15 @@ fn text(value: &b::lore_string_t) -> String {
String::from_utf8_lossy(bytes).into_owned() String::from_utf8_lossy(bytes).into_owned()
} }
/// Copies a liblore string array.
fn texts(value: &b::lore_string_array_t) -> Vec<String> {
if value.count == 0 || value.ptr.is_null() {
return Vec::new();
}
// SAFETY: liblore guarantees `count` strings at `ptr` for the callback's duration.
unsafe { std::slice::from_raw_parts(value.ptr, value.count) }.iter().map(text).collect()
}
pub fn hex(bytes: &[u8]) -> String { pub fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef"; const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2); let mut out = String::with_capacity(bytes.len() * 2);

View File

@ -15,7 +15,7 @@ use serde::Serialize;
use serde_json::Value; use serde_json::Value;
/// The protocol version this build speaks. /// The protocol version this build speaks.
pub const PROTOCOL_VERSION: u32 = 2; pub const PROTOCOL_VERSION: u32 = 3;
/// Overrides the directory holding the socket, configuration and log, for tests and for /// Overrides the directory holding the socket, configuration and log, for tests and for
/// running more than one service. /// running more than one service.
@ -42,6 +42,14 @@ pub mod methods {
pub const WORKSPACE_CLONE: &str = "workspace_clone"; pub const WORKSPACE_CLONE: &str = "workspace_clone";
pub const WORKSPACE_REMOVE: &str = "workspace_remove"; pub const WORKSPACE_REMOVE: &str = "workspace_remove";
pub const SHUTDOWN: &str = "shutdown"; pub const SHUTDOWN: &str = "shutdown";
/// `{workspace}` -> [`LocksResult`](crate::LocksResult): the current branch's locks.
pub const LOCKS: &str = "locks";
/// [`PathsParams`](crate::PathsParams) -> [`LockResult`](crate::LockResult).
pub const LOCK: &str = "lock";
/// [`UnlockParams`](crate::UnlockParams) -> [`UnlockResult`](crate::UnlockResult).
pub const UNLOCK: &str = "unlock";
/// [`WorkspaceSettingsParams`](crate::WorkspaceSettingsParams) -> the workspace.
pub const WORKSPACE_SETTINGS: &str = "workspace_settings";
} }
pub mod events { pub mod events {
@ -51,6 +59,10 @@ pub mod events {
pub const WORKSPACES: &str = "workspaces"; pub const WORKSPACES: &str = "workspaces";
/// A sign-in moved on: [`super::Login`]. /// A sign-in moved on: [`super::Login`].
pub const LOGIN: &str = "login"; pub const LOGIN: &str = "login";
/// [`LocksChanged`](crate::LocksChanged): a workspace's locks changed; ask `locks` again.
pub const LOCKS: &str = "locks";
/// [`Notice`](crate::Notice): something the user should hear about now.
pub const NOTICE: &str = "notice";
} }
/// JSON-RPC error codes. The standard ones, then ours from -32000. /// JSON-RPC error codes. The standard ones, then ours from -32000.
@ -72,6 +84,8 @@ pub mod codes {
pub const NO_LIBLORE: i64 = -32004; pub const NO_LIBLORE: i64 = -32004;
/// liblore refused or failed the operation; the message is liblore's. /// liblore refused or failed the operation; the message is liblore's.
pub const LORE_ERROR: i64 = -32005; pub const LORE_ERROR: i64 = -32005;
/// A submit included files someone else has locked.
pub const LOCKED: i64 = -32006;
} }
/// A request from a frontend. /// A request from a frontend.
@ -208,6 +222,21 @@ pub struct Workspace {
/// The last failure, until the next success. /// The last failure, until the next success.
#[serde(default)] #[serde(default)]
pub error: String, pub error: String,
/// Seconds between autosyncs; also the fallback check for `on_change`.
#[serde(default = "default_interval")]
pub interval_s: u64,
/// Lock binary files when they are first edited.
#[serde(default)]
pub lock_on_edit: bool,
/// Why autosync is holding back, until it can go on.
#[serde(default)]
pub warning: String,
}
pub const DEFAULT_INTERVAL_S: u64 = 300;
fn default_interval() -> u64 {
DEFAULT_INTERVAL_S
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -226,7 +255,9 @@ pub enum WorkspaceState {
pub enum Autosync { pub enum Autosync {
#[default] #[default]
Off, Off,
/// Every `interval_s`.
Interval, Interval,
/// As soon as someone pushes to the branch, and every `interval_s` as a fallback.
OnChange, OnChange,
} }
@ -241,6 +272,36 @@ pub struct SubmitParams {
pub message: String, pub message: String,
/// Repository-relative paths to commit; other local changes stay local. /// Repository-relative paths to commit; other local changes stay local.
pub paths: Vec<String>, pub paths: Vec<String>,
/// Keep your locks on the submitted files; by default the submit releases them.
#[serde(default)]
pub keep_locks: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathsParams {
pub workspace: String,
pub paths: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UnlockParams {
pub workspace: String,
pub paths: Vec<String>,
/// Release other people's locks too, which Lore allows repository admins.
#[serde(default)]
pub force: bool,
}
/// Changes to a workspace's policies; absent fields stay as they are.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct WorkspaceSettingsParams {
pub workspace: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub autosync: Option<Autosync>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_s: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock_on_edit: Option<bool>,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
@ -297,6 +358,11 @@ pub struct Change {
pub staged: bool, pub staged: bool,
#[serde(default)] #[serde(default)]
pub conflict: bool, pub conflict: bool,
/// Who holds the file's lock; empty when nobody does.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub lock: String,
#[serde(default)]
pub lock_mine: bool,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -398,6 +464,50 @@ pub struct RepositoriesResult {
pub repositories: Vec<Repository>, pub repositories: Vec<Repository>,
} }
/// A lock on the current branch.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lock {
pub path: String,
/// The holder's name, or their id when the name is unknown.
pub owner: String,
pub owner_id: String,
pub mine: bool,
pub locked_at_ms: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocksResult {
pub branch: String,
/// Yours first, then by path.
pub locks: Vec<Lock>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct LockResult {
/// Newly locked.
pub locked: Vec<String>,
/// Already yours.
pub already: Vec<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct UnlockResult {
pub released: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocksChanged {
pub workspace: String,
}
/// A warning for the user: autosync held back, an edit to a file someone else locked, a lock
/// that could not be taken.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Notice {
pub workspace: String,
pub message: String,
}
/// A sign-in's progress. /// A sign-in's progress.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Login { pub struct Login {

View File

@ -10,6 +10,7 @@ publish.workspace = true
[dependencies] [dependencies]
forge-protocol.workspace = true forge-protocol.workspace = true
lore-sys.workspace = true lore-sys.workspace = true
notify.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
tokio.workspace = true tokio.workspace = true

View File

@ -7,6 +7,10 @@
//! path = "/Users/me/lore/my-game" //! path = "/Users/me/lore/my-game"
//! remote = "lore://localhost:41337/me/my-game" # read from the working copy when empty //! remote = "lore://localhost:41337/me/my-game" # read from the working copy when empty
//! autosync = "off" # off, interval or on_change //! autosync = "off" # off, interval or on_change
//! interval_s = 300 # seconds between autosyncs
//! lock_on_edit = false # lock binary files when first edited
//! binary = ["fbx"] # extensions that count as binary whatever their content
//! text = ["svg"] # extensions that never do
//! ``` //! ```
use std::path::Path; use std::path::Path;
@ -31,6 +35,38 @@ pub struct WorkspaceConfig {
pub remote: String, pub remote: String,
#[serde(default)] #[serde(default)]
pub autosync: Autosync, pub autosync: Autosync,
#[serde(default = "default_interval", skip_serializing_if = "is_default_interval")]
pub interval_s: u64,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub lock_on_edit: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub binary: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub text: Vec<String>,
}
fn default_interval() -> u64 {
forge_protocol::DEFAULT_INTERVAL_S
}
fn is_default_interval(value: &u64) -> bool {
*value == forge_protocol::DEFAULT_INTERVAL_S
}
impl WorkspaceConfig {
/// A workspace with the default policies.
pub fn new(name: String, path: String, remote: String) -> WorkspaceConfig {
WorkspaceConfig {
name,
path,
remote,
autosync: Autosync::Off,
interval_s: default_interval(),
lock_on_edit: false,
binary: Vec::new(),
text: Vec::new(),
}
}
} }
impl Config { impl Config {
@ -100,12 +136,7 @@ mod tests {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub/desktop.toml"); let path = dir.path().join("sub/desktop.toml");
let config = Config { let config = Config {
workspaces: vec![WorkspaceConfig { workspaces: vec![WorkspaceConfig::new("game".into(), "/w/game".into(), String::new())],
name: "game".into(),
path: "/w/game".into(),
remote: String::new(),
autosync: Autosync::Off,
}],
}; };
config.save(&path).unwrap(); config.save(&path).unwrap();
let loaded = Config::load(&path).unwrap(); let loaded = Config::load(&path).unwrap();

View File

@ -79,6 +79,8 @@ pub fn changes(files: &[StatusFile]) -> Vec<Change> {
from: file.from.clone(), from: file.from.clone(),
staged: file.staged, staged: file.staged,
conflict: file.conflict_unresolved, conflict: file.conflict_unresolved,
lock: String::new(),
lock_mine: false,
}) })
}) })
.collect(); .collect();
@ -273,10 +275,90 @@ pub fn describe(operation: &str, error: &lore_sys::Error) -> String {
// "Local modifications prevent synchronization". // "Local modifications prevent synchronization".
44 => format!("{operation}: local edits to files changed on the remote; submit or revert them first"), 44 => format!("{operation}: local edits to files changed on the remote; submit or revert them first"),
40 => format!("{operation}: nothing to commit"), 40 => format!("{operation}: nothing to commit"),
// "Node not found": locking a path that is not in the working copy.
83 => format!("{operation}: no such file"),
_ if error.message.contains("resource already locked") => format!("{operation}: someone else holds the lock"),
_ if error.message.contains("locked by somebody else") => {
format!("{operation}: someone else holds the lock, and only a repository admin may release it")
}
_ => format!("{operation}: {error}"), _ => format!("{operation}: {error}"),
} }
} }
/// Whether Lore refused a sync because local edits overlap remote changes.
pub fn is_overlap(error: &lore_sys::Error) -> bool {
error.code == 44
}
/// Whether the file at `path` in `root` counts as binary for locking: by its extension when
/// `binary` or `text` lists it, else by a NUL byte in its first 8 KB, as git decides.
pub fn is_binary(root: &Path, path: &str, binary: &[String], text: &[String]) -> bool {
let extension = Path::new(path).extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
let listed = |list: &[String]| list.iter().any(|item| item.trim_start_matches('.').eq_ignore_ascii_case(&extension));
if !extension.is_empty() && listed(text) {
return false;
}
if !extension.is_empty() && listed(binary) {
return true;
}
let Ok(mut file) = std::fs::File::open(root.join(path)) else { return false };
let mut head = [0u8; 8192];
let mut filled = 0;
while filled < head.len() {
match std::io::Read::read(&mut file, &mut head[filled..]) {
Ok(0) | Err(_) => break,
Ok(n) => filled += n,
}
}
head[..filled].contains(&0)
}
/// Files changed on the remote branch since `signature` that are also changed locally.
/// `head` is the remote branch's newest revision when known (from a push notification);
/// otherwise the branch list says.
pub fn overlap(
lore: &Lore,
path: &str,
branch: &str,
signature: &str,
head: Option<String>,
local: &[String],
) -> Result<Vec<String>, lore_sys::Error> {
let globals = globals(path);
let mut head = head;
if head.is_none() {
lore.branch_list(&globals, |event| {
if let Event::Branch { name, latest, remote: true, .. } = event {
if name == branch {
head = latest;
}
}
})?;
}
let Some(head) = head.filter(|head| head != signature) else { return Ok(Vec::new()) };
let mut remote = Vec::new();
lore.revision_diff(&globals, signature, &head, |event| {
if let Event::DiffFile { path, file: true, .. } = event {
remote.push(path.trim_start_matches('/').to_owned());
}
})?;
let mut both: Vec<String> = local.iter().filter(|path| remote.contains(path)).cloned().collect();
both.sort();
both.dedup();
Ok(both)
}
/// "a.png", "a.png and b.png", "a.png, b.png and 3 more".
pub fn list_paths(paths: &[String]) -> String {
match paths {
[] => String::new(),
[one] => one.clone(),
[one, two] => format!("{one} and {two}"),
[one, two, three] => format!("{one}, {two} and {three}"),
[one, two, rest @ ..] => format!("{one}, {two} and {} more", rest.len()),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -373,6 +455,8 @@ mod tests {
from: String::new(), from: String::new(),
staged: false, staged: false,
conflict: false, conflict: false,
lock: String::new(),
lock_mine: false,
}; };
let changes = vec![change("a.txt", ChangeAction::Modify), change("gone.txt", ChangeAction::Delete), change("src/b.rs", ChangeAction::Add)]; let changes = vec![change("a.txt", ChangeAction::Modify), change("gone.txt", ChangeAction::Delete), change("src/b.rs", ChangeAction::Add)];
let locks = HashMap::from([("a.txt".to_owned(), ("bob".to_owned(), false))]); let locks = HashMap::from([("a.txt".to_owned(), ("bob".to_owned(), false))]);
@ -394,4 +478,30 @@ mod tests {
assert_eq!(sub[0].path, "src/b.rs"); assert_eq!(sub[0].path, "src/b.rs");
assert_eq!(sub[0].change, Some(ChangeAction::Add)); assert_eq!(sub[0].change, Some(ChangeAction::Add));
} }
#[test]
fn binary_files_by_content_and_by_extension() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("a.png"), [0x89, b'P', b'N', b'G', 0, 0, 0, 13]).unwrap();
std::fs::write(root.join("notes.txt"), "plain text").unwrap();
std::fs::write(root.join("mesh.fbx"), "; ASCII FBX").unwrap();
std::fs::write(root.join("icon.svg"), [b'<', 0, b'>']).unwrap();
let none: &[String] = &[];
assert!(is_binary(root, "a.png", none, none));
assert!(!is_binary(root, "notes.txt", none, none));
assert!(!is_binary(root, "mesh.fbx", none, none));
assert!(is_binary(root, "mesh.fbx", &[".FBX".into()], none));
assert!(!is_binary(root, "icon.svg", none, &["svg".into()]));
assert!(!is_binary(root, "missing.bin", none, none));
}
#[test]
fn path_lists_stay_short() {
let paths: Vec<String> = ["a", "b", "c", "d"].iter().map(|p| p.to_string()).collect();
assert_eq!(list_paths(&paths[..1]), "a");
assert_eq!(list_paths(&paths[..2]), "a and b");
assert_eq!(list_paths(&paths[..3]), "a, b and c");
assert_eq!(list_paths(&paths), "a, b and 2 more");
}
} }

View File

@ -54,7 +54,12 @@ fn main() -> ExitCode {
let service = Service::new(config, paths.config_file(), liblore); let service = Service::new(config, paths.config_file(), liblore);
// The service starts its Lore work once it holds the socket, not in a copy about to exit. // The service starts its Lore work once it holds the socket, not in a copy about to exit.
let result = runtime.block_on(listen::run(Arc::clone(&service), &paths)); let result = runtime.block_on(listen::run(Arc::clone(&service), &paths));
// Let liblore calls in flight finish, then drop the library, which flushes its stores. // End the notification subscriptions, let liblore calls in flight finish, then drop the
// library, which flushes its stores.
{
let _entered = runtime.enter();
service.stop_watching();
}
runtime.shutdown_timeout(Duration::from_secs(10)); runtime.shutdown_timeout(Duration::from_secs(10));
drop(service); drop(service);
match result { match result {

View File

@ -6,6 +6,7 @@
//! answers at once and reports through `activity` and `login` events. //! answers at once and reports through `activity` and `login` events.
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
@ -22,6 +23,11 @@ use forge_protocol::HelloParams;
use forge_protocol::HelloResult; use forge_protocol::HelloResult;
use forge_protocol::HistoryParams; use forge_protocol::HistoryParams;
use forge_protocol::HistoryResult; use forge_protocol::HistoryResult;
use forge_protocol::LocksChanged;
use forge_protocol::Notice;
use forge_protocol::PathsParams;
use forge_protocol::UnlockParams;
use forge_protocol::WorkspaceSettingsParams;
use forge_protocol::Liblore; use forge_protocol::Liblore;
use forge_protocol::Login; use forge_protocol::Login;
use forge_protocol::LoginPhase; use forge_protocol::LoginPhase;
@ -66,6 +72,11 @@ use crate::config::Config;
use crate::config::WorkspaceConfig; use crate::config::WorkspaceConfig;
use crate::lore; use crate::lore;
mod locks;
mod watch;
use watch::Watches;
/// The longest message accepted from a frontend. /// The longest message accepted from a frontend.
const MAX_LINE: u64 = 1 << 20; const MAX_LINE: u64 = 1 << 20;
/// How many branches `history` reads, and revisions per branch by default. /// How many branches `history` reads, and revisions per branch by default.
@ -81,6 +92,38 @@ struct Entry {
changes: Vec<Change>, changes: Vec<Change>,
/// A sync, submit or clone is running. /// A sync, submit or clone is running.
busy: bool, busy: bool,
/// Extensions that count as binary, or never do, for lock-on-edit.
binary: Vec<String>,
text: Vec<String>,
/// The current branch's locks by path: holder id and when taken. `None` until read.
locks: Option<HashMap<String, (String, u64)>>,
/// The repository's id, which notification subscriptions are shared by.
repository: String,
/// The current branch's id, for matching push notifications, and the remote head the
/// last one announced: a status scan does not learn of pushes by itself.
branch_id: String,
pushed_head: Option<String>,
/// Changed paths the last lock check saw, and those already warned about.
seen: HashSet<String>,
warned: HashSet<String>,
}
impl Entry {
fn new(config: &WorkspaceConfig) -> Entry {
Entry {
workspace: workspace_from(config),
changes: Vec::new(),
busy: false,
binary: config.binary.clone(),
text: config.text.clone(),
locks: None,
repository: String::new(),
branch_id: String::new(),
pushed_head: None,
seen: HashSet::new(),
warned: HashSet::new(),
}
}
} }
pub struct Service { pub struct Service {
@ -91,9 +134,13 @@ pub struct Service {
accounts: Mutex<Vec<Account>>, accounts: Mutex<Vec<Account>>,
/// User ids to names, as the remotes' user services resolved them. /// User ids to names, as the remotes' user services resolved them.
names: Mutex<HashMap<String, String>>, names: Mutex<HashMap<String, String>>,
/// Usernames from sign-ins: an account's label until a working copy can resolve its name.
signed_in_as: Mutex<HashMap<String, String>>,
/// Notifications, already serialized, for every client past `hello`. /// Notifications, already serialized, for every client past `hello`.
events: broadcast::Sender<String>, events: broadcast::Sender<String>,
shutdown: Notify, shutdown: Notify,
/// File watchers, notification subscriptions and autosync timers, by workspace.
watches: Watches,
} }
/// A workspace's id: stable for its path. /// A workspace's id: stable for its path.
@ -109,6 +156,9 @@ fn workspace_from(config: &WorkspaceConfig) -> Workspace {
remote: config.remote.clone(), remote: config.remote.clone(),
state: WorkspaceState::Unknown, state: WorkspaceState::Unknown,
autosync: config.autosync, autosync: config.autosync,
interval_s: config.interval_s.max(10),
lock_on_edit: config.lock_on_edit,
warning: String::new(),
branch: String::new(), branch: String::new(),
revision: 0, revision: 0,
signature: String::new(), signature: String::new(),
@ -133,9 +183,8 @@ impl Service {
pub fn new(config: Config, config_file: PathBuf, lore: Result<Arc<Lore>, String>) -> Arc<Service> { pub fn new(config: Config, config_file: PathBuf, lore: Result<Arc<Lore>, String>) -> Arc<Service> {
let mut workspaces: Vec<Entry> = Vec::new(); let mut workspaces: Vec<Entry> = Vec::new();
for workspace in &config.workspaces { for workspace in &config.workspaces {
let workspace = workspace_from(workspace); if !workspaces.iter().any(|entry| entry.workspace.id == workspace_id(&workspace.path)) {
if !workspaces.iter().any(|entry| entry.workspace.id == workspace.id) { workspaces.push(Entry::new(workspace));
workspaces.push(Entry { workspace, changes: Vec::new(), busy: false });
} }
} }
Arc::new(Service { Arc::new(Service {
@ -145,8 +194,10 @@ impl Service {
workspaces: Mutex::new(workspaces), workspaces: Mutex::new(workspaces),
accounts: Mutex::new(Vec::new()), accounts: Mutex::new(Vec::new()),
names: Mutex::new(HashMap::new()), names: Mutex::new(HashMap::new()),
signed_in_as: Mutex::new(HashMap::new()),
events: broadcast::channel(256).0, events: broadcast::channel(256).0,
shutdown: Notify::new(), shutdown: Notify::new(),
watches: Watches::default(),
}) })
} }
@ -161,6 +212,7 @@ impl Service {
service.refresh_accounts().await; service.refresh_accounts().await;
for id in service.ids() { for id in service.ids() {
service.refresh(&id).await; service.refresh(&id).await;
service.watch(&id);
} }
}); });
} }
@ -212,6 +264,17 @@ impl Service {
); );
} }
/// Tells frontends something the user should see now.
fn notice(&self, workspace: &str, message: impl Into<String>) {
let message = message.into();
tracing::info!(workspace, "{message}");
self.notify(events::NOTICE, Notice { workspace: workspace.into(), message });
}
fn locks_changed(&self, workspace: &str) {
self.notify(events::LOCKS, LocksChanged { workspace: workspace.into() });
}
fn save_config(&self) -> Result<(), Failure> { fn save_config(&self) -> Result<(), Failure> {
let config = Config { let config = Config {
workspaces: self workspaces: self
@ -224,6 +287,10 @@ impl Service {
path: entry.workspace.path.clone(), path: entry.workspace.path.clone(),
remote: entry.workspace.remote.clone(), remote: entry.workspace.remote.clone(),
autosync: entry.workspace.autosync, autosync: entry.workspace.autosync,
interval_s: entry.workspace.interval_s,
lock_on_edit: entry.workspace.lock_on_edit,
binary: entry.binary.clone(),
text: entry.text.clone(),
}) })
.collect(), .collect(),
}; };
@ -290,18 +357,27 @@ impl Service {
}) })
.await; .await;
let save = matches!(&read, Ok((_, remote)) if !remote.is_empty()); let save = matches!(&read, Ok((_, remote)) if !remote.is_empty());
let me = self.me();
let names = self.names.lock().unwrap().clone();
self.update(id, |entry| { self.update(id, |entry| {
let workspace = &mut entry.workspace; let workspace = &mut entry.workspace;
match read { match read {
Ok((position, remote)) => { Ok((position, remote)) => {
let status = position.status; let status = position.status;
entry.changes = lore::changes(&position.files); entry.changes = lore::changes(&position.files);
locks::annotate(&mut entry.changes, entry.locks.as_ref(), &me, &names);
// A push announced for another branch, or one we have reached, is done with.
if entry.branch_id != status.branch || entry.pushed_head == status.revision {
entry.pushed_head = None;
}
entry.branch_id = status.branch;
entry.repository = status.repository;
workspace.branch = status.branch_name; workspace.branch = status.branch_name;
workspace.revision = status.number; workspace.revision = status.number;
workspace.signature = status.revision.unwrap_or_default(); workspace.signature = status.revision.unwrap_or_default();
workspace.changes = entry.changes.len() as u64; workspace.changes = entry.changes.len() as u64;
workspace.ahead = status.local_ahead; workspace.ahead = status.local_ahead;
workspace.behind = status.remote_ahead; workspace.behind = status.remote_ahead || entry.pushed_head.is_some();
workspace.online = status.remote_available; workspace.online = status.remote_available;
workspace.signed_in = status.remote_authorized; workspace.signed_in = status.remote_authorized;
if !remote.is_empty() { if !remote.is_empty() {
@ -349,8 +425,13 @@ impl Service {
Some(path) => self.names_for(&path, unnamed).await, Some(path) => self.names_for(&path, unnamed).await,
None => self.names.lock().unwrap().clone(), None => self.names.lock().unwrap().clone(),
}; };
let usernames = self.signed_in_as.lock().unwrap().clone();
for account in &mut accounts { for account in &mut accounts {
account.name = names.get(&account.user_id).cloned().unwrap_or_default(); account.name = names
.get(&account.user_id)
.or_else(|| usernames.get(&account.user_id))
.cloned()
.unwrap_or_default();
} }
*self.accounts.lock().unwrap() = accounts; *self.accounts.lock().unwrap() = accounts;
} }
@ -432,8 +513,13 @@ impl Service {
if !params.paths.is_empty() && params.message.trim().is_empty() { if !params.paths.is_empty() && params.message.trim().is_empty() {
return Err((codes::INVALID_PARAMS, "a submit needs a message".into())); return Err((codes::INVALID_PARAMS, "a submit needs a message".into()));
} }
// Lore does not enforce locks on push, so the service does.
let held = self.held_by_others(&params.workspace, &params.paths).await?;
if !held.is_empty() {
return Err((codes::LOCKED, locks::describe_held(&held)));
}
let workspace = self.claim(&params.workspace)?; let workspace = self.claim(&params.workspace)?;
tokio::spawn(Arc::clone(&self).submit(workspace, params.message, params.paths)); tokio::spawn(Arc::clone(&self).submit(workspace, params.message, params.paths, params.keep_locks));
Ok(json!({})) Ok(json!({}))
} }
methods::CHANGES => { methods::CHANGES => {
@ -516,10 +602,51 @@ impl Service {
workspaces.remove(index); workspaces.remove(index);
workspaces.iter().map(|entry| entry.workspace.clone()).collect::<Vec<_>>() workspaces.iter().map(|entry| entry.workspace.clone()).collect::<Vec<_>>()
}; };
self.unwatch(&params.workspace).await;
self.save_config()?; self.save_config()?;
self.notify(events::WORKSPACES, list); self.notify(events::WORKSPACES, list);
Ok(json!({})) Ok(json!({}))
} }
methods::LOCKS => {
let params: WorkspaceParams = params(&request)?;
Ok(json!(self.locks(&params.workspace).await?))
}
methods::LOCK => {
let params: PathsParams = params(&request)?;
Ok(json!(self.lock(&params.workspace, params.paths).await?))
}
methods::UNLOCK => {
let params: UnlockParams = params(&request)?;
Ok(json!(self.unlock(&params.workspace, params.paths, params.force).await?))
}
methods::WORKSPACE_SETTINGS => {
let params: WorkspaceSettingsParams = params(&request)?;
self.workspace(&params.workspace)?;
self.update(&params.workspace, |entry| {
if let Some(autosync) = params.autosync {
entry.workspace.autosync = autosync;
}
if let Some(interval) = params.interval_s {
entry.workspace.interval_s = interval.max(10);
}
if let Some(lock_on_edit) = params.lock_on_edit {
entry.workspace.lock_on_edit = lock_on_edit;
}
if entry.workspace.autosync == forge_protocol::Autosync::Off {
entry.workspace.warning.clear();
}
});
self.save_config()?;
self.rewatch(&params.workspace);
if params.lock_on_edit == Some(true) {
// Files already edited count as first edits now.
self.update(&params.workspace, |entry| entry.seen.clear());
let service = Arc::clone(&self);
let id = params.workspace.clone();
tokio::spawn(async move { service.after_scan(&id).await });
}
Ok(json!(self.workspace(&params.workspace)?))
}
methods::SHUTDOWN => { methods::SHUTDOWN => {
tracing::info!("shutdown requested"); tracing::info!("shutdown requested");
self.shutdown.notify_one(); self.shutdown.notify_one();
@ -529,7 +656,9 @@ impl Service {
} }
} }
async fn sync(self: Arc<Self>, workspace: Workspace) { /// Pulls remote changes, keeping local edits. True when Lore refused because local edits
/// overlap them.
async fn sync(self: Arc<Self>, workspace: Workspace) -> bool {
let id = workspace.id.clone(); let id = workspace.id.clone();
self.activity(&id, "sync", Phase::Started, Some(0.0), "syncing"); self.activity(&id, "sync", Phase::Started, Some(0.0), "syncing");
let service = Arc::clone(&self); let service = Arc::clone(&self);
@ -548,10 +677,18 @@ impl Service {
_ => {} _ => {}
}); });
let _ = lore.repository_flush(&globals); let _ = lore.repository_flush(&globals);
synced.map_err(|error| lore_failure("sync", error))?; match synced {
Ok(outcome) Ok(()) => Ok(Ok(outcome)),
Err(error) if lore::is_overlap(&error) => Ok(Err(lore::describe("sync", &error))),
Err(error) => Err(lore_failure("sync", error)),
}
}) })
.await; .await;
let (result, overlap) = match result {
Ok(Ok(outcome)) => (Ok(outcome), false),
Ok(Err(message)) => (Err((codes::LORE_ERROR, message)), true),
Err(failure) => (Err(failure), false),
};
match result { match result {
Ok(outcome) => { Ok(outcome) => {
let message = match outcome { let message = match outcome {
@ -561,6 +698,7 @@ impl Service {
_ => "up to date".to_owned(), _ => "up to date".to_owned(),
}; };
self.release(&id, None); self.release(&id, None);
self.clear_warning(&id);
self.refresh(&id).await; self.refresh(&id).await;
self.activity(&id, "sync", Phase::Finished, Some(1.0), message); self.activity(&id, "sync", Phase::Finished, Some(1.0), message);
} }
@ -570,9 +708,12 @@ impl Service {
self.activity(&id, "sync", Phase::Failed, None, message); self.activity(&id, "sync", Phase::Failed, None, message);
} }
} }
overlap
} }
async fn submit(self: Arc<Self>, workspace: Workspace, message: String, paths: Vec<String>) { async fn submit(self: Arc<Self>, workspace: Workspace, message: String, paths: Vec<String>, keep_locks: bool) {
// The submitted files whose locks are ours, to release once pushed.
let mine: Vec<String> = if keep_locks { Vec::new() } else { self.held_by_me(&workspace.id, &paths) };
let id = workspace.id.clone(); let id = workspace.id.clone();
self.activity(&id, "submit", Phase::Started, Some(0.0), if paths.is_empty() { "pushing" } else { "staging" }); self.activity(&id, "submit", Phase::Started, Some(0.0), if paths.is_empty() { "pushing" } else { "staging" });
let service = Arc::clone(&self); let service = Arc::clone(&self);
@ -622,8 +763,17 @@ impl Service {
match result { match result {
Ok(committed) => { Ok(committed) => {
self.release(&id, None); self.release(&id, None);
let mut message = committed.map(|n| format!("submitted revision {n}")).unwrap_or_else(|| "pushed".into());
if !mine.is_empty() {
match self.unlock(&id, mine, false).await {
Ok(released) if !released.released.is_empty() => {
message.push_str(&format!("; released {}", lore::list_paths(&released.released)));
}
Ok(_) => {}
Err((_, error)) => self.notice(&id, format!("submitted, but the locks stay: {error}")),
}
}
self.refresh(&id).await; self.refresh(&id).await;
let message = committed.map(|n| format!("submitted revision {n}")).unwrap_or_else(|| "pushed".into());
self.activity(&id, "submit", Phase::Finished, Some(1.0), message); self.activity(&id, "submit", Phase::Finished, Some(1.0), message);
} }
Err((_, message)) => { Err((_, message)) => {
@ -669,7 +819,15 @@ impl Service {
lore.revision_info(&lore::globals(&path), &signature, true, true, |event| match event { lore.revision_info(&lore::globals(&path), &signature, true, true, |event| match event {
Event::Delta { path, action, modified, file, from } => { Event::Delta { path, action, modified, file, from } => {
if let (true, Some(action)) = (file, lore::change_action(action, modified)) { if let (true, Some(action)) = (file, lore::change_action(action, modified)) {
changes.push(Change { path, action, from, staged: false, conflict: false }); changes.push(Change {
path,
action,
from,
staged: false,
conflict: false,
lock: String::new(),
lock_mine: false,
});
} }
} }
other => collector.push(other), other => collector.push(other),
@ -704,29 +862,12 @@ impl Service {
.map(|entry| entry.changes.clone()) .map(|entry| entry.changes.clone())
.unwrap_or_default(); .unwrap_or_default();
// Locks need the remote; a listing without them is still useful. // Locks need the remote; a listing without them is still useful.
let path = workspace.path.clone(); let held = self.read_locks(id).await.unwrap_or_default();
let branch = workspace.branch.clone(); let me = self.me();
let locks = self let names = self.names.lock().unwrap().clone();
.blocking(move |lore| { let locks: HashMap<String, (String, bool)> = held
let mut locks = Vec::new();
lore.lock_file_query(&lore::globals(&path), &branch, |event| {
if let Event::Lock { path, owner, .. } = event {
locks.push((path, owner));
}
})
.map_err(|error| lore_failure("locks", error))?;
Ok(locks)
})
.await
.unwrap_or_default();
let me: Vec<String> = self.accounts.lock().unwrap().iter().map(|account| account.user_id.clone()).collect();
let names = self.names_for(&workspace.path, locks.iter().map(|(_, owner)| owner.clone()).collect()).await;
let locks: HashMap<String, (String, bool)> = locks
.into_iter() .into_iter()
.map(|(path, owner)| { .map(|(path, (owner, _))| (path, (names.get(&owner).cloned().unwrap_or_else(|| owner.clone()), me.contains(&owner))))
let name = names.get(&owner).cloned().unwrap_or_else(|| owner.clone());
(path.trim_start_matches('/').to_owned(), (name, me.contains(&owner)))
})
.collect(); .collect();
let root = PathBuf::from(&workspace.path); let root = PathBuf::from(&workspace.path);
let listing_dir = dir.clone(); let listing_dir = dir.clone();
@ -775,9 +916,12 @@ impl Service {
let login = |phase, message: String| Login { remote: remote.clone(), phase, url: String::new(), code: String::new(), message }; let login = |phase, message: String| Login { remote: remote.clone(), phase, url: String::new(), code: String::new(), message };
match result { match result {
Ok(user) => { Ok(user) => {
// The sign-in reports the username; names elsewhere come from the remote's user
// directory, which liblore gives as display names, so the username only labels
// the account until a working copy can resolve it.
let name = match user { let name = match user {
Some((id, name)) => { Some((id, name)) => {
self.names.lock().unwrap().insert(id, name.clone()); self.signed_in_as.lock().unwrap().insert(id, name.clone());
name name
} }
None => String::new(), None => String::new(),
@ -798,7 +942,7 @@ impl Service {
} }
} }
async fn workspace_add(&self, path: String) -> Result<Workspace, Failure> { async fn workspace_add(self: &Arc<Self>, path: String) -> Result<Workspace, Failure> {
let path = canonical(&path)?; let path = canonical(&path)?;
let lore = self.lore()?; let lore = self.lore()?;
let check = path.clone(); let check = path.clone();
@ -808,6 +952,7 @@ impl Service {
.map_err(|_| (codes::INVALID_PARAMS, format!("{path} is not a Lore working copy")))?; .map_err(|_| (codes::INVALID_PARAMS, format!("{path} is not a Lore working copy")))?;
let id = self.insert(&path, String::new())?; let id = self.insert(&path, String::new())?;
self.refresh(&id).await; self.refresh(&id).await;
self.watch(&id);
self.workspace(&id) self.workspace(&id)
} }
@ -858,6 +1003,7 @@ impl Service {
Ok(()) => { Ok(()) => {
self.release(&id, None); self.release(&id, None);
self.refresh(&id).await; self.refresh(&id).await;
self.watch(&id);
self.activity(&id, "clone", Phase::Finished, Some(1.0), "cloned"); self.activity(&id, "clone", Phase::Finished, Some(1.0), "cloned");
} }
Err((_, message)) => { Err((_, message)) => {
@ -881,8 +1027,7 @@ impl Service {
if workspaces.iter().any(|entry| entry.workspace.id == id) { if workspaces.iter().any(|entry| entry.workspace.id == id) {
return Err((codes::INVALID_PARAMS, format!("{path} is already a workspace"))); return Err((codes::INVALID_PARAMS, format!("{path} is already a workspace")));
} }
let config = WorkspaceConfig { name, path: path.to_owned(), remote, autosync: Default::default() }; workspaces.push(Entry::new(&WorkspaceConfig::new(name, path.to_owned(), remote)));
workspaces.push(Entry { workspace: workspace_from(&config), changes: Vec::new(), busy: false });
} }
self.save_config()?; self.save_config()?;
self.notify(events::WORKSPACES, self.workspaces()); self.notify(events::WORKSPACES, self.workspaces());
@ -1083,12 +1228,7 @@ mod tests {
/// A service without liblore, over a configuration file in `dir`. /// A service without liblore, over a configuration file in `dir`.
fn service(dir: &Path) -> Arc<Service> { fn service(dir: &Path) -> Arc<Service> {
let config = Config { let config = Config {
workspaces: vec![WorkspaceConfig { workspaces: vec![WorkspaceConfig::new("game".into(), "/w/game".into(), "lore://h/me/game".into())],
name: "game".into(),
path: "/w/game".into(),
remote: "lore://h/me/game".into(),
autosync: Default::default(),
}],
}; };
Service::new(config, dir.join("desktop.toml"), Err("not in tests".into())) Service::new(config, dir.join("desktop.toml"), Err("not in tests".into()))
} }

View File

@ -0,0 +1,364 @@
//! File locks: reading them, taking and releasing them, and the checks after each scan.
//!
//! Lore's locks are advisory: a push that changes a file someone else has locked is accepted
//! (checked against v0.14.0), so the service refuses such submits itself. Pushing does not
//! release a lock either; a submit releases the submitter's own locks unless asked not to.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use forge_protocol::Change;
use forge_protocol::ChangeAction;
use forge_protocol::Lock;
use forge_protocol::LockResult;
use forge_protocol::LocksResult;
use forge_protocol::UnlockResult;
use forge_protocol::codes;
use lore_sys::Event;
use super::Failure;
use super::Service;
use super::lore_failure;
use crate::lore;
/// Locks by path: the holder's user id and when they took it.
pub type Held = HashMap<String, (String, u64)>;
/// Marks each change with who holds its lock.
pub fn annotate(changes: &mut [Change], locks: Option<&Held>, me: &[String], names: &HashMap<String, String>) {
for change in changes {
match locks.and_then(|locks| locks.get(&change.path)) {
Some((owner, _)) => {
change.lock = names.get(owner).cloned().unwrap_or_else(|| owner.clone());
change.lock_mine = me.contains(owner);
}
None => {
change.lock.clear();
change.lock_mine = false;
}
}
}
}
/// "a.png is locked by bob", for a submit or lock refused over other people's locks.
pub fn describe_held(held: &[(String, String)]) -> String {
let mut by_owner: Vec<(String, Vec<String>)> = Vec::new();
for (path, owner) in held {
match by_owner.iter_mut().find(|(name, _)| name == owner) {
Some((_, paths)) => paths.push(path.clone()),
None => by_owner.push((owner.clone(), vec![path.clone()])),
}
}
let parts: Vec<String> = by_owner
.into_iter()
.map(|(owner, paths)| {
let verb = if paths.len() == 1 { "is" } else { "are" };
format!("{} {verb} locked by {owner}", lore::list_paths(&paths))
})
.collect();
parts.join("; ")
}
fn relative(paths: &[String]) -> Result<Vec<String>, Failure> {
let mut out = Vec::new();
for path in paths {
let path = path.trim_matches('/');
if path.is_empty() || path.split('/').any(|part| part.is_empty() || part == "." || part == "..") {
return Err((codes::INVALID_PARAMS, format!("{path:?} is not a repository-relative path")));
}
out.push(path.to_owned());
}
if out.is_empty() {
return Err((codes::INVALID_PARAMS, "choose the files".into()));
}
Ok(out)
}
impl Service {
/// The signed-in users' ids.
pub(super) fn me(&self) -> Vec<String> {
self.accounts.lock().unwrap().iter().map(|account| account.user_id.clone()).collect()
}
/// Reads the current branch's locks, keeps them, and marks the local changes. On failure
/// (offline, say) the last locks read stay.
pub(super) async fn read_locks(&self, id: &str) -> Result<Held, Failure> {
let workspace = self.workspace(id)?;
let path = workspace.path.clone();
let branch = workspace.branch.clone();
let read = self
.blocking(move |lore| {
let mut held = Held::new();
lore.lock_file_query(&lore::globals(&path), &branch, |event| {
if let Event::Lock { path, owner, locked_at, .. } = event {
held.insert(path.trim_start_matches('/').to_owned(), (owner, locked_at));
}
})
.map_err(|error| lore_failure("locks", error))?;
Ok(held)
})
.await;
let held = match read {
Ok(held) => held,
Err(error) => {
let kept = self.with_entry(id, |entry| entry.locks.clone()).flatten();
return kept.ok_or(error);
}
};
let names = self.names_for(&workspace.path, held.values().map(|(owner, _)| owner.clone()).collect()).await;
let me = self.me();
let stored = held.clone();
self.update(id, |entry| {
annotate(&mut entry.changes, Some(&stored), &me, &names);
entry.locks = Some(stored);
});
Ok(held)
}
/// Runs `read` on a workspace's entry, if it is still there.
pub(super) fn with_entry<T>(&self, id: &str, read: impl FnOnce(&super::Entry) -> T) -> Option<T> {
self.workspaces.lock().unwrap().iter().find(|entry| entry.workspace.id == id).map(read)
}
/// Paths among `paths` someone else holds, with the holder's name, from fresh locks.
pub(super) async fn held_by_others(&self, id: &str, paths: &[String]) -> Result<Vec<(String, String)>, Failure> {
if paths.is_empty() {
return Ok(Vec::new());
}
let held = match self.read_locks(id).await {
Ok(held) => held,
// No locks readable and none known: nothing to refuse on.
Err(_) => return Ok(Vec::new()),
};
let me = self.me();
let names = self.names.lock().unwrap().clone();
Ok(paths
.iter()
.filter_map(|path| {
let (owner, _) = held.get(path)?;
(!me.contains(owner)).then(|| (path.clone(), names.get(owner).cloned().unwrap_or_else(|| owner.clone())))
})
.collect())
}
/// Paths among `paths` whose locks are ours, from the locks last read.
pub(super) fn held_by_me(&self, id: &str, paths: &[String]) -> Vec<String> {
let me = self.me();
self.with_entry(id, |entry| {
let Some(locks) = &entry.locks else { return Vec::new() };
paths.iter().filter(|path| locks.get(*path).is_some_and(|(owner, _)| me.contains(owner))).cloned().collect()
})
.unwrap_or_default()
}
pub(super) async fn locks(&self, id: &str) -> Result<LocksResult, Failure> {
self.lore()?;
let held = self.read_locks(id).await?;
let workspace = self.workspace(id)?;
let me = self.me();
let names = self.names.lock().unwrap().clone();
let mut locks: Vec<Lock> = held
.into_iter()
.map(|(path, (owner_id, locked_at))| Lock {
path,
owner: names.get(&owner_id).cloned().unwrap_or_else(|| owner_id.clone()),
mine: me.contains(&owner_id),
owner_id,
locked_at_ms: locked_at,
})
.collect();
locks.sort_by(|a, b| b.mine.cmp(&a.mine).then_with(|| a.path.cmp(&b.path)));
Ok(LocksResult { branch: workspace.branch, locks })
}
pub(super) async fn lock(&self, id: &str, paths: Vec<String>) -> Result<LockResult, Failure> {
let paths = relative(&paths)?;
let workspace = self.workspace(id)?;
let held = self.held_by_others(id, &paths).await?;
if !held.is_empty() {
return Err((codes::LOCKED, describe_held(&held)));
}
let path = workspace.path.clone();
let result = self
.blocking(move |lore| {
let mut result = LockResult::default();
let mut ignored = false;
lore.lock_file_acquire(&lore::globals(&path), &paths, "", |event| match event {
Event::LockAcquireBegin { ignored: flag } => ignored = flag,
Event::LockAcquired { path } => {
let path = path.trim_start_matches('/').to_owned();
if ignored { result.already.push(path) } else { result.locked.push(path) }
}
_ => {}
})
.map_err(|error| lore_failure("lock", error))?;
Ok(result)
})
.await;
// Whatever happened, the locks may have changed.
let _ = self.read_locks(id).await;
self.locks_changed(id);
result
}
/// Releases our locks on `paths`; with `force`, other people's too.
pub(super) async fn unlock(&self, id: &str, paths: Vec<String>, force: bool) -> Result<UnlockResult, Failure> {
let paths = relative(&paths)?;
let workspace = self.workspace(id)?;
let held = self.read_locks(id).await?;
let me = self.me();
let mut own = Vec::new();
let mut others: HashMap<String, Vec<String>> = HashMap::new();
for path in &paths {
match held.get(path) {
Some((owner, _)) if !me.contains(owner) => others.entry(owner.clone()).or_default().push(path.clone()),
_ => own.push(path.clone()),
}
}
if !force && !others.is_empty() {
let names = self.names.lock().unwrap().clone();
let list: Vec<(String, String)> = others
.iter()
.flat_map(|(owner, paths)| {
let name = names.get(owner).cloned().unwrap_or_else(|| owner.clone());
paths.iter().map(move |path| (path.clone(), name.clone()))
})
.collect();
return Err((codes::LOCKED, format!("{}; FORCE UNLOCK releases other people's locks", describe_held(&list))));
}
let path = workspace.path.clone();
let result = self
.blocking(move |lore| {
let globals = lore::globals(&path);
let mut released = Vec::new();
let mut groups: Vec<(String, Vec<String>)> = others.into_iter().collect();
if !own.is_empty() {
groups.insert(0, (String::new(), own));
}
for (owner_id, paths) in groups {
lore.lock_file_release(&globals, &paths, "", "", &owner_id, |event| {
if let Event::LockReleased { path } = event {
released.push(path.trim_start_matches('/').to_owned());
}
})
.map_err(|error| lore_failure("unlock", error))?;
}
released.sort();
Ok(UnlockResult { released })
})
.await;
let _ = self.read_locks(id).await;
self.locks_changed(id);
result
}
/// After a scan: warns about edits to files someone else holds, once per file, and with
/// lock-on-edit takes the locks of binary files edited for the first time.
pub(super) async fn after_scan(self: &Arc<Self>, id: &str) {
let Some(busy) = self.with_entry(id, |entry| entry.busy) else { return };
if busy || self.lore.is_err() {
return;
}
if self.with_entry(id, |entry| entry.locks.is_none()) == Some(true) && self.read_locks(id).await.is_err() {
return;
}
let me = self.me();
let names = self.names.lock().unwrap().clone();
let Some((fresh, held, lock_on_edit, root, binary, text)) = self.with_entry(id, |entry| {
let fresh: Vec<Change> = entry.changes.iter().filter(|change| !entry.seen.contains(&change.path)).cloned().collect();
(
fresh,
entry.locks.clone().unwrap_or_default(),
entry.workspace.lock_on_edit,
PathBuf::from(&entry.workspace.path),
entry.binary.clone(),
entry.text.clone(),
)
}) else {
return;
};
let mut warn = Vec::new();
let mut candidates = Vec::new();
for change in &fresh {
match held.get(&change.path) {
Some((owner, _)) if !me.contains(owner) => {
warn.push((change.path.clone(), names.get(owner).cloned().unwrap_or_else(|| owner.clone())));
}
Some(_) => {}
None if lock_on_edit && change.action == ChangeAction::Modify => candidates.push(change.path.clone()),
None => {}
}
}
let to_lock = tokio::task::spawn_blocking(move || {
candidates.into_iter().filter(|path| lore::is_binary(&root, path, &binary, &text)).collect::<Vec<_>>()
})
.await
.unwrap_or_default();
let warned_before = self.with_entry(id, |entry| entry.warned.clone()).unwrap_or_default();
let warn: Vec<(String, String)> = warn.into_iter().filter(|(path, _)| !warned_before.contains(path)).collect();
self.update(id, |entry| {
let current: std::collections::HashSet<String> = entry.changes.iter().map(|change| change.path.clone()).collect();
entry.warned.retain(|path| current.contains(path));
entry.warned.extend(warn.iter().map(|(path, _)| path.clone()));
entry.seen = current;
});
if !warn.is_empty() {
self.notice(id, format!("{}; your edits stay local until the lock is released", describe_held(&warn)));
}
if !to_lock.is_empty() {
match self.lock(id, to_lock.clone()).await {
Ok(result) if !result.locked.is_empty() => {
tracing::info!(workspace = id, "locked on edit: {}", lore::list_paths(&result.locked));
}
Ok(_) => {}
Err((_, error)) => self.notice(id, format!("could not lock {}: {error}", lore::list_paths(&to_lock))),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn change(path: &str) -> Change {
Change {
path: path.into(),
action: ChangeAction::Modify,
from: String::new(),
staged: false,
conflict: false,
lock: String::new(),
lock_mine: false,
}
}
#[test]
fn annotates_changes_with_holders() {
let mut changes = vec![change("a.png"), change("b.png"), change("c.txt")];
let held: Held = [("a.png".to_owned(), ("u-me".to_owned(), 1)), ("b.png".to_owned(), ("u-bob".to_owned(), 2))].into();
let names: HashMap<String, String> = [("u-bob".to_owned(), "bob".to_owned())].into();
annotate(&mut changes, Some(&held), &["u-me".to_owned()], &names);
assert_eq!((changes[0].lock.as_str(), changes[0].lock_mine), ("u-me", true));
assert_eq!((changes[1].lock.as_str(), changes[1].lock_mine), ("bob", false));
assert_eq!((changes[2].lock.as_str(), changes[2].lock_mine), ("", false));
}
#[test]
fn describes_held_files_by_holder() {
let held = vec![
("a.png".to_owned(), "bob".to_owned()),
("b.png".to_owned(), "bob".to_owned()),
("c.png".to_owned(), "eve".to_owned()),
];
assert_eq!(describe_held(&held), "a.png and b.png are locked by bob; c.png is locked by eve");
}
#[test]
fn lock_paths_must_be_relative() {
assert_eq!(relative(&["/a/b.png".into()]).unwrap(), vec!["a/b.png"]);
assert!(relative(&["../x".into()]).is_err());
assert!(relative(&[]).is_err());
}
}

View File

@ -0,0 +1,442 @@
//! What runs beside each workspace while the service is up:
//!
//! - a file watcher: an edit rescans the working copy (debounced), then runs the lock checks;
//! - a notification subscription on its own thread: pushes and lock changes from the server.
//! liblore keeps one subscription per repository in a process (a second replaces the first,
//! and unsubscribing ends both), so working copies of one repository share it;
//! - the autosync timer.
//!
//! Autosync only pulls; SUBMIT pushes. When local edits overlap what the remote changed, it
//! holds back and warns rather than let Lore refuse the sync or anything be overwritten.
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use std::time::Instant;
use forge_protocol::Autosync;
use lore_sys::Event;
use lore_sys::Lore;
use notify::RecursiveMode;
use notify::Watcher;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use super::Service;
use crate::lore;
/// How long the working copy must be quiet before a rescan.
const SETTLE: Duration = Duration::from_millis(800);
/// Resubscription backoff after a subscription ends or fails.
const BACKOFF_MIN: Duration = Duration::from_secs(5);
const BACKOFF_MAX: Duration = Duration::from_secs(60);
/// The running watches by workspace id, and the notification subscriptions by repository id.
#[derive(Default)]
pub struct Watches {
workspaces: Mutex<HashMap<String, Watch>>,
repositories: Mutex<HashMap<String, Subscription>>,
}
struct Watch {
/// The repository whose subscription this workspace shares, if any.
repository: String,
_files: Option<notify::RecommendedWatcher>,
tasks: Vec<tokio::task::JoinHandle<()>>,
/// Wakes the autosync timer when the settings change.
wake: Arc<Notify>,
}
/// One repository's subscription, and the workspaces its events go to.
struct Subscription {
/// The working copy the subscription was made through.
path: String,
members: Arc<Mutex<Vec<String>>>,
stop: Arc<AtomicBool>,
/// Dropped to wake the subscriber from its backoff.
stop_tx: Option<std_mpsc::Sender<()>>,
thread: Option<std::thread::JoinHandle<()>>,
task: tokio::task::JoinHandle<()>,
}
/// Whether a changed path is Lore's own bookkeeping rather than the user's files.
fn ignored(root: &Path, path: &Path) -> bool {
let Ok(relative) = path.strip_prefix(root) else { return true };
match relative.components().next() {
Some(first) => {
let first = first.as_os_str().to_string_lossy();
first == ".lore" || first.starts_with(".urc")
}
None => true,
}
}
/// Ends a subscription, waiting briefly for its thread. liblore must not shut down while a
/// call is running.
fn end(mut subscription: Subscription, lore: &Lore) {
subscription.stop.store(true, Ordering::SeqCst);
subscription.stop_tx = None;
subscription.task.abort();
let Some(thread) = subscription.thread.take() else { return };
let globals = lore::globals(&subscription.path);
let deadline = Instant::now() + Duration::from_secs(5);
while !thread.is_finished() && Instant::now() < deadline {
// A subscription still connecting ignores this, so keep asking until it ends.
let _ = lore.notification_unsubscribe(&globals, |_| {});
std::thread::sleep(Duration::from_millis(50));
}
if thread.is_finished() {
let _ = thread.join();
} else {
tracing::warn!(path = subscription.path, "notification subscription did not end");
}
}
/// Subscribes through the working copy at `path`, resubscribing with backoff whenever the
/// subscription ends, and hands every event to each member workspace.
fn subscribe(service: &Arc<Service>, lore: Arc<Lore>, path: String, members: Arc<Mutex<Vec<String>>>) -> Subscription {
let stop_flag = Arc::new(AtomicBool::new(false));
let (events_tx, mut events_rx) = mpsc::unbounded_channel::<Event>();
let (stop_tx, stop_rx) = std_mpsc::channel::<()>();
let thread = {
let stop_flag = Arc::clone(&stop_flag);
let path = path.clone();
std::thread::Builder::new()
.name("lore-notifications".into())
.spawn(move || {
let mut backoff = BACKOFF_MIN;
while !stop_flag.load(Ordering::SeqCst) {
let started = Instant::now();
let result = lore.notification_subscribe(&lore::globals(&path), |event| {
let _ = events_tx.send(event);
});
if stop_flag.load(Ordering::SeqCst) {
break;
}
tracing::debug!(path, "notification subscription ended: {result:?}");
if started.elapsed() > BACKOFF_MAX {
backoff = BACKOFF_MIN;
}
match stop_rx.recv_timeout(backoff) {
Err(std_mpsc::RecvTimeoutError::Timeout) => {}
_ => break,
}
backoff = (backoff * 2).min(BACKOFF_MAX);
}
})
.map_err(|error| tracing::warn!("cannot start the notification thread: {error}"))
.ok()
};
let task = {
let service = Arc::clone(service);
let members = Arc::clone(&members);
tokio::spawn(async move {
while let Some(event) = events_rx.recv().await {
let ids = members.lock().unwrap().clone();
for id in ids {
service.on_notification(&id, event.clone()).await;
}
}
})
};
Subscription { path, members, stop: stop_flag, stop_tx: Some(stop_tx), thread, task }
}
impl Service {
/// Starts watching a workspace, if liblore is there and it is not watched yet.
pub(super) fn watch(self: &Arc<Self>, id: &str) {
let Ok(lore) = self.lore() else { return };
let Ok(workspace) = self.workspace(id) else { return };
let repository = self.with_entry(id, |entry| entry.repository.clone()).unwrap_or_default();
let mut watches = self.watches.workspaces.lock().unwrap();
if watches.contains_key(id) {
return;
}
let path = workspace.path.clone();
let wake = Arc::new(Notify::new());
let mut tasks = Vec::new();
// Notifications: shared by the repository's working copies.
if !repository.is_empty() {
let mut subscriptions = self.watches.repositories.lock().unwrap();
match subscriptions.get(&repository) {
Some(subscription) => subscription.members.lock().unwrap().push(id.to_owned()),
None => {
let members = Arc::new(Mutex::new(vec![id.to_owned()]));
subscriptions.insert(repository.clone(), subscribe(self, lore, path.clone(), members));
}
}
}
// Files: rescans once the working copy has been quiet for a moment.
let (files_tx, mut files_rx) = mpsc::unbounded_channel::<()>();
let root = PathBuf::from(&path);
let files = notify::recommended_watcher(move |result: notify::Result<notify::Event>| {
let Ok(event) = result else { return };
if matches!(event.kind, notify::EventKind::Access(_)) {
return;
}
if event.paths.iter().all(|changed| ignored(&root, changed)) {
return;
}
let _ = files_tx.send(());
})
.and_then(|mut watcher| watcher.watch(Path::new(&path), RecursiveMode::Recursive).map(|()| watcher))
.map_err(|error| tracing::warn!(path, "cannot watch the working copy: {error}"))
.ok();
{
let service = Arc::clone(self);
let id = id.to_owned();
tasks.push(tokio::spawn(async move {
while files_rx.recv().await.is_some() {
loop {
tokio::time::sleep(SETTLE).await;
let mut more = false;
while files_rx.try_recv().is_ok() {
more = true;
}
if !more {
break;
}
}
if service.with_entry(&id, |entry| entry.busy) != Some(false) {
continue;
}
service.refresh(&id).await;
service.after_scan(&id).await;
}
}));
}
// Autosync.
{
let service = Arc::clone(self);
let id = id.to_owned();
let wake = Arc::clone(&wake);
tasks.push(tokio::spawn(async move {
// The first check comes after the start-up refresh and lock checks.
service.after_scan(&id).await;
let mut woken = false;
while let Some((autosync, interval)) =
service.with_entry(&id, |entry| (entry.workspace.autosync, entry.workspace.interval_s))
{
if woken && autosync != Autosync::Off {
service.autosync(&id, None).await;
}
let wait = if autosync == Autosync::Off { 3600 } else { interval };
tokio::select! {
() = tokio::time::sleep(Duration::from_secs(wait)) => {
woken = false;
if autosync != Autosync::Off {
service.autosync(&id, None).await;
}
}
() = wake.notified() => woken = true,
}
}
}));
}
watches.insert(id.to_owned(), Watch { repository, _files: files, tasks, wake });
}
/// The workspace's settings changed: the autosync timer starts over, syncing now if on.
pub(super) fn rewatch(&self, id: &str) {
if let Some(watch) = self.watches.workspaces.lock().unwrap().get(id) {
watch.wake.notify_one();
}
}
/// Stops watching a workspace. Its repository's subscription ends with its last member; if
/// it was made through this working copy, it is made again through another.
pub(super) async fn unwatch(self: &Arc<Self>, id: &str) {
let Some(watch) = self.watches.workspaces.lock().unwrap().remove(id) else { return };
for task in &watch.tasks {
task.abort();
}
let Ok(lore) = self.lore() else { return };
let ending = {
let mut subscriptions = self.watches.repositories.lock().unwrap();
let Some(subscription) = subscriptions.get(&watch.repository) else { return };
let remaining: Vec<String> = {
let mut members = subscription.members.lock().unwrap();
members.retain(|member| member != id);
members.clone()
};
let through_this = self.with_entry(id, |entry| entry.workspace.path.clone()).as_ref() == Some(&subscription.path)
|| !remaining.iter().any(|member| {
self.with_entry(member, |entry| entry.workspace.path.clone()).as_ref() == Some(&subscription.path)
});
if remaining.is_empty() || through_this {
subscriptions.remove(&watch.repository).map(|subscription| (subscription, remaining))
} else {
None
}
};
let Some((subscription, remaining)) = ending else { return };
let ended = Arc::clone(&lore);
let _ = tokio::task::spawn_blocking(move || end(subscription, &ended)).await;
if let Some(path) = remaining.first().and_then(|member| self.with_entry(member, |entry| entry.workspace.path.clone())) {
let members = Arc::new(Mutex::new(remaining));
let renewed = subscribe(self, lore, path, members);
self.watches.repositories.lock().unwrap().insert(watch.repository, renewed);
}
}
/// Stops every watch and subscription. Called once the service has stopped serving,
/// before liblore shuts down.
pub fn stop_watching(&self) {
for (_, watch) in self.watches.workspaces.lock().unwrap().drain() {
for task in &watch.tasks {
task.abort();
}
}
let subscriptions: Vec<Subscription> =
self.watches.repositories.lock().unwrap().drain().map(|(_, subscription)| subscription).collect();
let Ok(lore) = self.lore() else { return };
for subscription in subscriptions {
end(subscription, &lore);
}
}
async fn on_notification(self: &Arc<Self>, id: &str, event: Event) {
tracing::debug!(workspace = id, "notification: {event:?}");
match event {
Event::Subscribed { .. } => tracing::debug!(workspace = id, "subscribed to notifications"),
Event::ResourcesLocked { paths, user_id, .. } if !paths.is_empty() => {
let _ = self.read_locks(id).await;
self.locks_changed(id);
if !self.me().contains(&user_id) {
let edited: Vec<String> = self
.with_entry(id, |entry| {
entry.changes.iter().filter(|change| paths.contains(&change.path)).map(|change| change.path.clone()).collect()
})
.unwrap_or_default();
if !edited.is_empty() {
let names = self.names.lock().unwrap().clone();
let who = names.get(&user_id).cloned().unwrap_or(user_id);
let verb = if edited.len() == 1 { "which you have" } else { "which you have all" };
self.notice(id, format!("{who} locked {}, {verb} edited", lore::list_paths(&edited)));
self.update(id, |entry| entry.warned.extend(edited));
}
}
}
Event::ResourcesUnlocked { paths, .. } if !paths.is_empty() => {
let _ = self.read_locks(id).await;
self.locks_changed(id);
}
Event::BranchPushed { branch, signature, .. } => {
// A status scan does not learn of the push; the notification says what moved.
let ours = self.with_entry(id, |entry| entry.branch_id == branch && entry.workspace.signature != signature);
tracing::debug!(workspace = id, ?ours, "push to {branch}");
if ours == Some(true) {
let head = signature.clone();
self.update(id, |entry| {
entry.pushed_head = Some(head);
entry.workspace.behind = true;
});
if self.with_entry(id, |entry| entry.workspace.autosync) == Some(Autosync::OnChange) {
self.autosync(id, Some(signature)).await;
}
}
}
Event::BranchCreated { .. } | Event::BranchDeleted { .. } => self.refresh(id).await,
_ => {}
}
}
/// Pulls if the remote moved and nothing local would be overwritten; otherwise warns.
/// `head` is the remote branch's new revision, when a push notification said; without it
/// (the interval) the sync itself finds out, and is quietly up to date when nothing moved.
pub(super) async fn autosync(self: &Arc<Self>, id: &str, head: Option<String>) {
match self.with_entry(id, |entry| (entry.busy, entry.workspace.autosync)) {
Some((false, autosync)) if autosync != Autosync::Off => {}
_ => return,
}
self.refresh(id).await;
let Ok(workspace) = self.workspace(id) else { return };
tracing::debug!(workspace = id, ?head, online = workspace.online, signed_in = workspace.signed_in, "autosync");
if !workspace.online || !workspace.signed_in {
return;
}
if head.as_deref() == Some(workspace.signature.as_str()) {
self.clear_warning(id);
return;
}
let local: Vec<String> =
self.with_entry(id, |entry| entry.changes.iter().map(|change| change.path.clone()).collect()).unwrap_or_default();
if !local.is_empty() {
let path = workspace.path.clone();
let branch = workspace.branch.clone();
let signature = workspace.signature.clone();
let overlap = self
.blocking(move |lore| {
lore::overlap(lore, &path, &branch, &signature, head, &local)
.map_err(|error| super::lore_failure("autosync", error))
})
.await;
match overlap {
Ok(paths) if !paths.is_empty() => {
self.warn(id, overlap_warning(&paths));
return;
}
Ok(_) => {}
Err((_, error)) => tracing::debug!(workspace = id, "cannot compare with the remote: {error}"),
}
}
let Ok(workspace) = self.claim(id) else { return };
if Arc::clone(self).sync(workspace).await {
// Lore refused after all: the remote moved again since the comparison.
self.warn(id, "autosync held back: local edits overlap remote changes; submit or revert them".into());
}
}
/// Sets a workspace's warning, telling frontends once per new warning.
fn warn(&self, id: &str, message: String) {
if self.with_entry(id, |entry| entry.workspace.warning == message) == Some(true) {
return;
}
let shown = message.clone();
self.update(id, |entry| entry.workspace.warning = message);
self.notice(id, shown);
}
pub(super) fn clear_warning(&self, id: &str) {
if self.with_entry(id, |entry| !entry.workspace.warning.is_empty()) == Some(true) {
self.update(id, |entry| entry.workspace.warning.clear());
}
}
}
fn overlap_warning(paths: &[String]) -> String {
format!("autosync held back: local edits to {} overlap remote changes; submit or revert them", lore::list_paths(paths))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lore_bookkeeping_is_ignored() {
let root = Path::new("/w/game");
assert!(ignored(root, Path::new("/w/game/.lore/index")));
assert!(ignored(root, Path::new("/w/game/.urc-tmp/x")));
assert!(ignored(root, Path::new("/elsewhere/a.png")));
assert!(!ignored(root, Path::new("/w/game/art/a.png")));
assert!(!ignored(root, Path::new("/w/game/.lorekeep")));
}
#[test]
fn overlap_warning_names_the_files() {
assert_eq!(
overlap_warning(&["a.png".into(), "b.png".into()]),
"autosync held back: local edits to a.png and b.png overlap remote changes; submit or revert them"
);
}
}

View File

@ -2,16 +2,25 @@
"""Drives forge-service over its socket as the desktop GUI would, against a real loreserver """Drives forge-service over its socket as the desktop GUI would, against a real loreserver
and lore-forge. Run by scripts/e2e-lore.sh, which starts everything and passes: and lore-forge. Run by scripts/e2e-lore.sh, which starts everything and passes:
desktop-e2e.py SOCKET FORGE_URL COOKIE_JAR LORE_REMOTE WORK_DIR desktop-e2e.py SOCKET FORGE_URL COOKIE_JAR LORE_REMOTE WORK_DIR LORE_CLI BOB_WORKING_COPY
Signs in through the device flow (approving it as the cookie jar's user), lists and clones Signs in through the device flow (approving it as the cookie jar's user), lists and clones
alice/demo, reads files, history and a revision, submits some of the local changes, then adds alice/demo, reads files, history and a revision, submits some of the local changes, then adds
the CLI's working copy and syncs it. Exits nonzero with a message on the first failure. the CLI's working copy and syncs it.
Then locks and policies, with bob (a writer on alice/demo, through the `lore` CLI in his own
working copy) on the other side: bob's lock reaches alice's service, her edit to his file is
warned about and refused on submit, she force-releases it, a submit releases her own locks,
lock-on-edit takes the lock of an edited binary file, autosync pulls bob's push, and holds
back when her edits overlap his.
Exits nonzero with a message on the first failure.
""" """
import json import json
import os import os
import socket import socket
import subprocess
import sys import sys
import time import time
import urllib.parse import urllib.parse
@ -33,6 +42,7 @@ class Service:
self.buffer = b"" self.buffer = b""
self.next_id = 0 self.next_id = 0
self.notifications = [] self.notifications = []
self.notices = []
self.responses = {} self.responses = {}
def _read(self): def _read(self):
@ -45,6 +55,8 @@ class Service:
message = json.loads(line) message = json.loads(line)
if "method" in message: if "method" in message:
self.notifications.append(message) self.notifications.append(message)
if message["method"] == "notice":
self.notices.append(message["params"]["message"])
else: else:
self.responses[message["id"]] = message self.responses[message["id"]] = message
@ -65,6 +77,35 @@ class Service:
fail(f"{method}: {answer['error']['message']}") fail(f"{method}: {answer['error']['message']}")
return answer["result"] return answer["result"]
def refused(self, method, params, code):
"""Calls `method` expecting error `code`; returns the error message."""
answer = self.response(self.send(method, params))
if "error" not in answer:
fail(f"{method} {params} was not refused")
if answer["error"]["code"] != code:
fail(f"{method} was refused with {answer['error']}, not code {code}")
return answer["error"]["message"]
def until(self, what, check, timeout=TIMEOUT_S):
"""Polls `check` (which may make calls) until it returns something true."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
value = check()
if value:
return value
time.sleep(0.3)
fail(f"timed out waiting for {what}")
def notice(self, text, timeout=TIMEOUT_S):
"""Waits for a notice containing `text`."""
def seen():
# A cheap call reads whatever has arrived.
self.call("status")
return next((n for n in self.notices if text in n), None)
return self.until(f"a notice about {text!r}", seen, timeout)
def wait(self, method, match): def wait(self, method, match):
"""The first notification `method` whose params satisfy `match`, dropping those before.""" """The first notification `method` whose params satisfy `match`, dropping those before."""
deadline = time.monotonic() + TIMEOUT_S deadline = time.monotonic() + TIMEOUT_S
@ -110,12 +151,12 @@ def approve(forge, jar, code):
def main(): def main():
sock_path, forge, jar, remote, work = sys.argv[1:6] sock_path, forge, jar, remote, work, lore_cli, bob_wc = sys.argv[1:8]
service = Service(sock_path) service = Service(sock_path)
step = lambda text: print(f" {text}") step = lambda text: print(f" {text}")
hello = service.call("hello", {"protocol": 2, "client": "desktop-e2e"}) hello = service.call("hello", {"protocol": 3, "client": "desktop-e2e"})
step(f"hello: {hello['service']}") step(f"hello: {hello['service']}")
status = service.call("status") status = service.call("status")
if "loaded" not in status["liblore"]: if "loaded" not in status["liblore"]:
@ -133,6 +174,7 @@ def main():
if done["phase"] != "done" or done.get("message") != "alice": if done["phase"] != "done" or done.get("message") != "alice":
fail(f"sign-in ended {done}") fail(f"sign-in ended {done}")
accounts = service.call("status")["accounts"] accounts = service.call("status")["accounts"]
# With no working copy yet to resolve names through, the account carries the username.
if not any(a.get("name") == "alice" for a in accounts): if not any(a.get("name") == "alice" for a in accounts):
fail(f"status does not list alice's account: {accounts}") fail(f"status does not list alice's account: {accounts}")
step("signed in as alice") step("signed in as alice")
@ -164,8 +206,9 @@ def main():
for want in ["First revision", "Second revision", "Feature work", "Main moves on"]: for want in ["First revision", "Second revision", "Feature work", "Main moves on"]:
if want not in messages: if want not in messages:
fail(f"history lacks {want!r}: {messages}") fail(f"history lacks {want!r}: {messages}")
# liblore names the signed-in user by username and others by display name.
if any(r["author"] != "alice" for r in history["revisions"] if r["message"]): if any(r["author"] != "alice" for r in history["revisions"] if r["message"]):
fail("history does not name alice as the author") fail(f"history does not name alice as the author: {sorted({r['author'] for r in history['revisions']})}")
merge = history["revisions"][0] merge = history["revisions"][0]
if len(merge["parents"]) != 2: if len(merge["parents"]) != 2:
fail(f"the newest revision is not the merge: {merge}") fail(f"the newest revision is not the merge: {merge}")
@ -220,8 +263,127 @@ def main():
step(f"working copy synced to r{newest['number']}, local.txt kept") step(f"working copy synced to r{newest['number']}, local.txt kept")
service.call("workspace_remove", {"workspace": cli_ws}) service.call("workspace_remove", {"workspace": cli_ws})
locks_and_policies(service, ws, into, lore_cli, bob_wc)
service.call("shutdown") service.call("shutdown")
def write(path, text):
with open(path, "w") as f:
f.write(text)
def read(path):
with open(path) as f:
return f.read()
def locks_and_policies(service, ws, into, lore_cli, bob_wc):
step = lambda text: print(f" {text}")
bob_env = dict(os.environ, LORE_AUTH_PATH=os.path.join(os.path.dirname(bob_wc), "auth-bob"))
def bob(*args):
done = subprocess.run([lore_cli, *args], cwd=bob_wc, env=bob_env, capture_output=True, text=True)
if done.returncode != 0:
fail(f"bob: lore {' '.join(args)}: {done.stdout}{done.stderr}")
return done.stdout
def locks():
return {l["path"]: l for l in service.call("locks", {"workspace": ws})["locks"]}
def changes():
return {c["path"]: c for c in service.call("changes", {"workspace": ws})["changes"]}
# kept.txt is still a local change from the submit above; it stays out of the way.
got = service.call("lock", {"workspace": ws, "paths": ["a.txt"]})
if got["locked"] != ["a.txt"]:
fail(f"lock answered {got}")
if service.call("lock", {"workspace": ws, "paths": ["a.txt"]})["already"] != ["a.txt"]:
fail("locking again does not report the lock as already held")
mine = locks().get("a.txt")
if not mine or not mine["mine"] or mine["owner"] != "alice":
fail(f"locks shows {mine}")
step("alice locks a.txt")
bob("sync")
bob("lock", "acquire", "d.txt")
held = service.until("bob's lock to reach alice", lambda: locks().get("d.txt"))
if held["mine"] or held["owner"] != "Bob Example":
fail(f"bob's lock shows as {held}")
step("bob's lock on d.txt reaches alice's service")
write(os.path.join(into, "d.txt"), "alice's edit\n")
service.notice("d.txt is locked by Bob Example")
change = service.until("d.txt in changes", lambda: changes().get("d.txt"))
if change["lock"] != "Bob Example" or change["lock_mine"]:
fail(f"changes shows d.txt as {change}")
message = service.refused("submit", {"workspace": ws, "message": "Over bob's lock", "paths": ["d.txt"]}, -32006)
if "d.txt is locked by Bob Example" not in message:
fail(f"the refusal says {message!r}")
service.refused("lock", {"workspace": ws, "paths": ["d.txt"]}, -32006)
service.refused("unlock", {"workspace": ws, "paths": ["d.txt"]}, -32006)
step("alice's edit to d.txt is warned about; submit, lock and unlock are refused")
released = service.call("unlock", {"workspace": ws, "paths": ["d.txt"], "force": True})["released"]
if released != ["d.txt"] or "d.txt" in locks():
fail(f"force unlock released {released}")
step("alice, the repository's owner, force-releases bob's lock")
write(os.path.join(into, "a.txt"), "six\n")
service.until("a.txt in changes", lambda: "a.txt" in changes())
service.call("submit", {"workspace": ws, "message": "Locked edits", "paths": ["a.txt", "d.txt"]})
done = service.finished(ws, "submit")
if "released a.txt" not in done["message"] or locks():
fail(f"the submit did not release a.txt: {done['message']!r}, locks {locks()}")
step(f"submit releases alice's lock ({done['message']})")
# Lock on edit: a tracked binary file, and a text file beside it.
with open(os.path.join(into, "art.bin"), "wb") as f:
f.write(b"\x00\x01art")
service.until("art.bin in changes", lambda: "art.bin" in changes())
service.call("submit", {"workspace": ws, "message": "Add art", "paths": ["art.bin"]})
service.finished(ws, "submit")
settings = service.call("workspace_settings", {"workspace": ws, "lock_on_edit": True})
if not settings["lock_on_edit"]:
fail(f"workspace_settings answered {settings}")
with open(os.path.join(into, "art.bin"), "wb") as f:
f.write(b"\x00\x02art")
write(os.path.join(into, "e.txt"), "text edit\n")
taken = service.until("the lock on art.bin", lambda: locks().get("art.bin"))
if not taken["mine"] or "e.txt" in locks():
fail(f"lock on edit took {sorted(locks())}")
service.call("submit", {"workspace": ws, "message": "Edit art", "paths": ["art.bin", "e.txt"]})
service.finished(ws, "submit")
if locks():
fail(f"locks left after submitting art.bin: {sorted(locks())}")
step("lock on edit locks the edited binary file, not the text file")
# Autosync on change: bob's push arrives without a sync from alice.
service.call("workspace_settings", {"workspace": ws, "autosync": "on_change", "lock_on_edit": False})
bob("sync")
write(os.path.join(bob_wc, "c.txt"), "bob's art\n")
bob("stage", "c.txt")
bob("commit", "Bob updates c.txt")
bob("push")
service.until("autosync to bring c.txt", lambda: read(os.path.join(into, "c.txt")) == "bob's art\n")
step("autosync pulls bob's push")
# Overlapping edits: autosync holds back and warns; alice's edit stays.
write(os.path.join(into, "c.txt"), "alice's art\n")
service.until("c.txt in changes", lambda: "c.txt" in changes())
bob("sync")
write(os.path.join(bob_wc, "c.txt"), "bob's second art\n")
bob("stage", "c.txt")
bob("commit", "Bob updates c.txt again")
bob("push")
service.notice("autosync held back: local edits to c.txt overlap remote changes")
status = {w["id"]: w for w in service.call("status")["workspaces"]}[ws]
if "c.txt" not in status["warning"] or not status["behind"]:
fail(f"the workspace shows {status}")
if read(os.path.join(into, "c.txt")) != "alice's art\n":
fail("autosync overwrote alice's edit")
step("autosync holds back over alice's overlapping edit, and says so")
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -18,8 +18,8 @@
# does the same for lore-forge. # does the same for lore-forge.
# #
# Then it runs the desktop client's forge-service, linked to the pinned liblore, through # Then it runs the desktop client's forge-service, linked to the pinned liblore, through
# scripts/desktop-e2e.py: sign-in, clone, the explorer's reads, submit and sync. NO_DESKTOP=1 # scripts/desktop-e2e.py: sign-in, clone, the explorer's reads, submit and sync, then locks,
# skips that. # lock-on-edit and autosync against bob in his own working copy. NO_DESKTOP=1 skips that.
# #
# HOLD=1 keeps both servers running after the browser checks, for a look at the pages. # HOLD=1 keeps both servers running after the browser checks, for a look at the pages.
# #
@ -343,6 +343,7 @@ if [ -z "${NO_DESKTOP:-}" ]; then
export LORE_FORGE_DESKTOP_DIR="$WORK/desktop" export LORE_FORGE_DESKTOP_DIR="$WORK/desktop"
export LORE_FORGE_LIBLORE="$LIBLORE_DIR/$LIBLORE_FILE" export LORE_FORGE_LIBLORE="$LIBLORE_DIR/$LIBLORE_FILE"
export LORE_AUTH_PATH="$WORK/auth-desktop" export LORE_AUTH_PATH="$WORK/auth-desktop"
export RUST_LOG="${RUST_LOG:-info,forge_service=debug}"
exec "$ROOT/desktop/target/debug/forge-service" exec "$ROOT/desktop/target/debug/forge-service"
) >"$WORK/desktop/stdout.log" 2>&1 & ) >"$WORK/desktop/stdout.log" 2>&1 &
DESKTOP_PID=$! DESKTOP_PID=$!
@ -352,8 +353,12 @@ if [ -z "${NO_DESKTOP:-}" ]; then
kill -0 "$DESKTOP_PID" 2>/dev/null || { cat "$WORK/desktop/stdout.log" >&2; fail "forge-service exited"; } kill -0 "$DESKTOP_PID" 2>/dev/null || { cat "$WORK/desktop/stdout.log" >&2; fail "forge-service exited"; }
sleep 0.2 sleep 0.2
done done
# bob writes to alice/demo from his own working copy, for the lock checks.
alice_post /alice/demo/access kind=user name=bob preset=writer >/dev/null
(cd "$WORK" && LORE_AUTH_PATH="$WORK/auth-bob" "$LORE" clone "$LORE_REMOTE/alice/demo" bob-demo) >/dev/null
python3 -I "$ROOT/scripts/desktop-e2e.py" "$WORK/desktop/service.sock" "$FORGE" "$JAR" "$LORE_REMOTE" "$WORK" \ python3 -I "$ROOT/scripts/desktop-e2e.py" "$WORK/desktop/service.sock" "$FORGE" "$JAR" "$LORE_REMOTE" "$WORK" \
|| { tail -20 "$WORK/desktop/service.log" >&2; fail "the desktop service checks failed"; } "$LORE" "$WORK/bob-demo" \
|| { tail -20 "$WORK/desktop/stdout.log" >&2; fail "the desktop service checks failed"; }
wait "$DESKTOP_PID" || fail "forge-service did not stop cleanly" wait "$DESKTOP_PID" || fail "forge-service did not stop cleanly"
fi fi