A Laravel backend
An Elyra app can be the desktop half of a product whose web half is Laravel, served by Askr or any other server. The app signs the user in with a Sanctum token, calls the same API as the web, and shows Laravel's validation messages in its forms as if they were its own. Changes made on the web show in its windows, it keeps working offline, and Laravel's notifications reach the desktop. The design is RFC 0005.
In five lines
elyra = { …, features = ["backend"] } # with "database" for make:resource
App::new().backend(Backend::new("https://crm.example.com"))
#[command(live, can = "customers.view")]
async fn customers_index(ctx: Ctx, query: CustomerQuery) -> elyra::Result<Page<Customer>> {
Ok(ctx.get::<Backend>().get("/api/customers").query(&query).json().await?)
}
<script>
import { auth } from "@elyra/runtime";
</script>
{#if $auth.signedIn}Hi {$auth.user.name}{:else}<SignIn />{/if}
Or generate the whole resource, with its screens:
rata make:resource Customer --backend /api/customers --generate name:string email:email.
The Laravel side
Sanctum and three routes, in routes/api.php (Laravel prefixes them with
/api, as Backend expects):
php artisan install:api # Sanctum; then add `HasApiTokens` to App\Models\User
Route::post('/sanctum/token', function (Request $request) {
$request->validate(['email' => 'required|email', 'password' => 'required', 'device_name' => 'required']);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages(['email' => ['The provided credentials are incorrect.']]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
Route::middleware('auth:sanctum')->group(function () {
Route::delete('/sanctum/token', fn (Request $r) => $r->user()->currentAccessToken()->delete());
Route::get('/user', fn (Request $r) => $r->user());
Route::apiResource('customers', CustomerController::class);
});
Different paths? Backend::new(url).token_route(..).revoke_route(..).user_route(..).
scripts/laravel-backend.sh builds a complete
app like this. CI runs Elyra against it.
The Composer package elyracode/elyra-backend, in
this repository, has these routes as Route::elyraAuth(), the
idempotency middleware, and the
notifications controller as
Route::elyraNotifications(), and what .broadcasting_from(..) and
UpdaterConfig::from_backend(..) read as Route::elyraBroadcasting() and
Route::elyraUpdates(). It also gives Laravel Boost guidelines and a
skill, so agents working on the Laravel app keep what the desktop relies on
(coding agents). It isn't on Packagist yet:
its README says how to add it from a clone of this repository.
Route::elyraAuth();
Route::middleware(['auth:sanctum', Elyra\Backend\Http\Middleware\Idempotent::class])->group(function () {
Route::elyraNotifications();
Route::apiResource('customers', CustomerController::class);
});
Calling the API
let backend = ctx.get::<Backend>();
let page: Page<Customer> = backend.get("/api/customers").query(&query).json().await?;
let customer: Customer = backend.get(format!("/api/customers/{id}")).resource().await?;
let created: Customer = backend.post("/api/customers").body(&input).resource().await?;
backend.delete(format!("/api/customers/{id}")).send().await?;
- The token: it's sent as
Bearerwhen the user is signed in. Requests ask for JSON, which is what makes Laravel answer a failed validation with422JSON instead of a redirect. .json()and.resource():.json()decodes the body as the type. A204decodes as()..resource()also unwraps an API Resource's{ "data": … }, so a controller can return a model or a resource.- Pages:
Page<T>reads both of Laravel's paginators,paginate()'s flat one and an API Resource collection's{ data, links, meta }, and a list'stotalsbesidedataor inmeta(lists). - Nested query values go as PHP reads them:
.query(&json!({ "filters": { "status": ["open"], "amount": { "min": 10000 } } }))isfilters[status][]=open&filters[amount][min]=10000;nulland empty lists are left out, aboolis1or0. - The rest of the request:
.query,.header,.timeoutand.retrywork as onHttp, whichBackendis built on. - Updates send the whole record. An
Optionthat'sNonegoes asnull, which is what a form means. For a partialPATCH, mark the fields#[serde(skip_serializing_if = "Option::is_none")].
Lists: searched, filtered and totalled
A Table over a list on the server sends its search, its filters, its sort
and its page (RFC 0071); the
package's elyraList answers them, on any Eloquent query:
public function index(Request $request)
{
return Invoice::query()->elyraList($request, [
'search' => ['number', 'customer'],
'sort' => ['number', 'due', 'amount'],
'filters' => ['status' => 'options', 'amount' => 'range', 'due' => 'dates', 'customer' => 'text'],
'totals' => ['amount' => 'sum'],
'groups' => ['customer', 'status'],
]);
}
| Option | From the request | Does |
|---|---|---|
search |
search |
any of the columns contains the term, ignoring case |
sort |
sort, direction |
a listed column, else the key; then the key |
filters |
filters[...] |
text contains, options one of, range min/max, dates from/to by day |
totals |
— | sum, avg, min, max or count over every matching row |
groups |
group |
a listed column orders the page first, and each group on it has its count and totals (RFC 0074) |
per_page, max_per_page |
per_page |
25 by default, at most 100 |
- Only what's listed is let through. A filter on a column the options
don't name, a kind not its own (a list sent for a
range), a sort that isn't allowed: each is ignored. Every value is bound;%and_in a search or a text filter are themselves, not wildcards. - The totals are the list's, over every row that matched, before the
page: the
Table's foot says "Total" for them, not "This page". A sum or a count of nothing is 0. - A grouped list (
group=customer, a column ingroups) is ordered by it first, so a group's rows are together across pages, and answersgroups: each group on the page, keyed by its value as the row's JSON has it (""for none), with itscountand thetotalsover every row of it that matched. ATable's header says a group's whole even where the page cuts it. - The answer is Laravel's paginator with
totals(andgroups) besidedata(ElyraPaginator); under an API Resource collection they're inmeta, whichPage<T>reads too. make:resource --backendwrites the desktop's half: a typed{Model}Filtersin the list's query, and the columns' filters. The controller is yours; rata prints theelyraListcall that matches.
Many rows at once
A Table sets one column for many selected rows in calls of 500 keys
(RFC 0084): PATCH /api/invoices with { "ids": [...], "values": { "status": "paid" } }. The package answers it
(RFC 0086):
Route::patch('invoices', [InvoiceController::class, 'updateMany']); // before the resource
Route::apiResource('invoices', InvoiceController::class);
public function updateMany(Request $request)
{
return Invoice::query()->elyraUpdateMany($request, [
'rules' => ['status' => 'sometimes|required|in:open,paid', 'due' => 'sometimes|nullable|date'],
'columns' => ['status', 'due'],
]);
}
- Only what's given: the fields in
values, each validated with itsrules(a 422 as a form's). A field not incolumnsrefuses the request; auniqueone for more than one id too. At mostmaxids (500). - Each row's policy:
ability(updateby default) is asked of each model, through the query (its scopes apply); a row the policy refuses, or a key not found, is infailedwith the message. - One transaction: each row that passes is saved (
forceFill, its events, casts andupdated_at), or with'quietly' => trueoneupdate()on their keys. - The answer:
{ "updated": 238, "failed": { "12": "This invoice is locked." } }; the desktop marks the failed rows. rata make:resource --backendprints the method for a resource.
Many rows deleted
The selection's Delete (RFC 0087) is DELETE /api/invoices with { "ids": [...] }, answered by the package:
Route::delete('invoices', [InvoiceController::class, 'destroyMany']); // before the resource
public function destroyMany(Request $request)
{
return Invoice::query()->elyraDestroyMany($request);
}
Each row is found through the query and asked its policy (ability,
delete by default); the ones that pass are deleted in one transaction,
each with delete() (soft deletes, events and observers as usual). The
answer is { "deleted": 338, "failed": { "12": "This invoice is locked." } }.
The trash
For a model with SoftDeletes, elyraList's 'trashed' => true answers
the trash's trashed=only (and with), and the package restores:
Route::post('invoices/restore', [InvoiceController::class, 'restoreMany']); // before the resource
public function restoreMany(Request $request)
{
return Invoice::query()->elyraRestoreMany($request);
}
Each deleted row is found through the query and asked its restore
policy; the ones that pass are restored in one transaction. A key that
isn't deleted is in failed ("Not deleted."). The answer is { "restored": 2, "failed": {} } (RFC 0088).
Saved views on the server
A list's saved views (RFC 0070) are kept on the server when the app asks for them there (RFC 0076): the user's own on every machine they sign in on, and the ones shared with the team.
Backend::new("https://crm.example.com").views()
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
Route::elyraViews();
});
// app/Providers/AppServiceProvider.php
public function boot(): void
{
\Elyra\Backend\ElyraBackend::views(); // the elyra_views table, for `php artisan migrate`
}
| Route | Does |
|---|---|
GET /elyra/views?list=customers |
the user's views of the list, and the shared ones; can_share |
POST /elyra/views |
saves one: list, name, definition, shared |
PUT /elyra/views/{id} |
renames it, saves its definition again, or shares it |
DELETE /elyra/views/{id} |
deletes it |
- The list is the
Table'spersist; the definition is RFC 0070's view (filters,search,sort,direction,group,columns), kept as the desktop sent it, at most 16 KB, never read by the server. - Sharing needs the ability
elyra.views.share: a Gate, or a permission (spatie's), the app grants. Without it, no one shares. A shared view is changed or deleted by its owner, or by a user who may share; a name is the user's once per list, and a shared one the team's once per list (a422onnameotherwise). - Offline, a list's last answer (kept in the settings store) is read, and a write waits in the outbox (working offline). Signing out forgets the copies.
- Each write broadcasts
ElyraViewsChangedon the user's channel, so their other machines read the list again; a teammate's shared view is seen the next time the menu opens. - The first time a machine reads a list's views from the server, its own (kept by 0.63–0.65 in the settings store) are saved there, unshared, and the machine's copy deleted.
- A server without the routes (
404) keeps the views on the machine, as an app without.views()does.php artisan vendor:publish --tag=elyra-viewscopies the migration, for an app that edits it.
Laravel's answers
| Laravel | BackendError |
The frontend sees |
|---|---|---|
422 { errors } |
Validation |
a ValidationError, per field, as from a local command |
401, 419 |
Unauthenticated |
kind unauthenticated; the token is forgotten and elyra:auth says expired |
403 { message } |
Forbidden |
kind denied, with Laravel's message |
404 |
NotFound |
kind not-found |
409, 412 |
Conflict |
kind conflict, with Laravel's message (see Conflicts) |
429 + Retry-After |
TooManyRequests |
kind too-many-requests, saying when |
5xx |
Server |
kind server, without the error page |
| no answer | Unreachable |
kind offline |
? in a command turns each into the right error. The kind reaches the
frontend as CommandError.kind, from a command and from a live query's
re-run, so the UI can say "you're offline" rather than show an error.
Working offline adds two that Laravel never sends. A
write that waits in the outbox is Queued, kind queued, and signing out
with writes waiting is PendingChanges, kind pending_changes.
Signing in
let auth = ctx.get::<Auth>();
auth.sign_in("ada@example.com", "secret").await?; // a 422 for bad credentials
let user: User = auth.user().await?; // GET /api/user, cached
auth.sign_out().await?; // revoke, forget
- The token lives in the OS keychain only, never in the webview or a file. It's restored when the app starts, so a signed-in user stays signed in. With no keychain (Linux without Secret Service), sign-in fails, and the token the server just issued is revoked.
- The device is named
<host> · <app>, so the user recognizes it among their tokens on the web. - A
401from any request signs the user out, andelyra:authcarries{ signedIn: false, reason: "expired" }.
From the frontend, through /__auth/* (Capability::Auth, granted by
default):
import { auth, onSignedOut, ValidationError } from "@elyra/runtime";
try {
await auth.signIn(email, password);
} catch (e) {
if (e instanceof ValidationError) errors = e.errors; // { email: ["…"] }
}
$auth; // { signedIn, user, reason }
onSignedOut((reason) => reason === "expired" && toast("Please sign in again"));
A server chosen at sign-in
Some products aren't one server. Each company runs its own, and the user
types its address on the sign-in screen. Backend::chosen_at_sign_in()
is a backend with no server until then
(RFC 0021):
App::new().backend(
Backend::chosen_at_sign_in()
.user_route("/api/v1/me")
.broadcasting_from("/api/desktop/broadcasting"),
)
-
Every builder method works as for
Backend::new(url). The routes are paths, and the broadcaster's socket goes to the chosen server's host unless the settings say otherwise. -
Before a server is chosen, a request fails with
BackendError::NoServer, kindunauthenticated, as for a user who isn't signed in. Nothing is sent anywhere. The UI shows its sign-in screen, as it would anyway. -
Auth::sign_in_with_tokenchooses it (below). The address is normalised (https://acme.example.com/ishttps://acme.example.com) and must be anhttporhttpsURL. -
It's remembered while the user is signed in. It's in the keychain under
backend-server, beside the token, which is underbackend-token:<server>as for any backend. At the next start the app is signed in to the same server. -
Signing out forgets it, and so does a
401. The next start shows the sign-in screen. If the app wants to fill the address in for the user, it keeps it itself (it isn't a secret: the store will do). -
The broadcasting settings come from the server with
.broadcasting_from(path), since each server has its own Reverb or Pusher and the app can't know its key when it's built. After each sign-in or switch, and at a start that restores one, the app sends aGETto the path as the user, before it connects. The answer looks like this:{ "key": "…", "host": "ws.acme.example.com", "port": 443, "scheme": "wss" }host,portandschememay be left out. They default as forBroadcasting::pusher(key), to the server's own host. A{ "data": … }wrapper is fine. Nothing of it is kept: the key is public, and it's read again each time. No answer (or a5xx, a429) is tried again with the connection's backoff. A404, a403, or settings without a key leave broadcasting off for this sign-in, with a warning in the log. Everything else works. The follows and the auth route are still the app's. For an auth route other than/api/broadcasting/auth, add.broadcasting(Broadcasting::pusher("").auth_route(..)); its key is replaced by the server's.Route::elyraBroadcasting()fromelyracode/elyra-backendserves it, inside theauth:sanctumgroup: the default broadcast connection's key, host, port and scheme (Reverb'sREVERB_*, or Pusher's, its socket host from the cluster). When the desktop reaches Reverb at another address than Laravel publishes to, as behind a proxy,ELYRA_BROADCASTING_HOST,_PORTand_SCHEMEsay which. Without a Reverb or Pusher connection it's a404, and the desktop runs without broadcasting. -
backend.base_url()is the server,Noneuntil it's chosen.Auth::sign_in(email, password)needs one too: with none, it fails withNoServeras any request does.
A token from elsewhere
Auth::sign_in posts an email and password to Sanctum's token route. An app
that signs in another way, such as OAuth's device authorization grant
through the browser (SSO, 2FA), ends up holding a token and the user's
profile. sign_in_with_token adopts them:
let me: Value = /* the profile the device grant's last step answered */;
ctx.get::<Auth>()
.sign_in_with_token("https://acme.example.com", &access_token, me)
.await?;
From then on it's as after sign_in. Requests carry the token, the
broadcaster connects, the abilities are read, notifications arrive, and
elyra:auth says { signedIn: true, user }.
- The server: for
Backend::chosen_at_sign_in(), the first argument chooses it. ForBackend::new(url), it must be that server, written any way that normalises to it. Another one is an error: an app with a fixed server can't be pointed elsewhere. - The token is kept in the keychain as
sign_inkeeps one. With no keychain, it fails withBackendError::Keychainand nothing changes. It isn't revoked: the app got it, and the app decides. - The user value is what
auth.user()returns and whatelyra:authcarries, without asking the server. It isn't kept across restarts: at the next start it's read fromuser_routethe first time it's needed. A keychain entry is the wrong place for a profile, which can be larger than Windows allows (2.5 KB) and goes stale. So pointuser_routeat a route that answers the same shape. - The user's id names the user's channel, the user among presence
members, and whose offline copy it is. It's at
idunless.user_id_path("user.id")says otherwise, for a route that answers{ "user": { "id": 7 }, "workspace": { … } }. - Signing out works as before.
sign_out()revokes the token atrevoke_route(aDELETE, as the user) and forgets it, so point that route at whatever revokes this kind of token.
Switching
A user in several workspaces of the same product may hold one token per
workspace, each scoped to its workspace. The app keeps those in its own
keychain entries, and lets the user switch between them as Slack does.
Switching means calling sign_in_with_token again while signed in, with the
other token and its profile:
auth.sign_in_with_token(&server, &tokens.get(workspace)?, me).await?;
- No sign-out between.
elyra:authis sent once,{ signedIn: true }with the new user, so the$authstore goes from one user to the other.onSignedOutisn't called. - The broadcaster reconnects with the new token. It subscribes to the app's channels again, and to the channels named from the user as the new user names them.
- The abilities are read again. They're forgotten first, so there's no moment with the last workspace's.
- Everything live that read the backend re-runs. Every backend read
depends on
backend::ALL_KEYas well as its resource. - Notifications are counted again from the new user's list, once the broadcaster has reconnected.
- The server's offline copy of reads is dropped. Another token's
answers to the same URL can differ (another workspace), so none is ever
answered from the last one's. With
a copy per workspace, each keeps its own
instead. Other servers' copies stay. The outbox
stays: each write waits for its own user's turn. A switch that keeps the
user's id but changes the token would send the waiting writes with the
new token, so it's refused with
PendingChanges(kindpending_changes) until they're sent or discarded. - Another server needs a sign-out first, unless the backend is signed in to several at once.
A copy per workspace
Dropping the copy at each switch is safe, but a user who moves between
workspaces all day loses it each time, and can't switch while a write
waits. .offline_scope_path(..) says where the workspace is in the user
value. The copy and the outbox are then kept per workspace as well as per
user:
Backend::chosen_at_sign_in()
.user_route("/api/v1/me") // { "user": { "id": 7 }, "workspace": { "id": 3 } }
.user_id_path("user.id")
.offline_scope_path("workspace.id")
- A switch keeps the last workspace's copy. Each workspace answers only from its own, so switching back while offline still shows what it last read.
- A write waits for its own workspace. It's sent only while that workspace is the one signed in to, with its token, so a switch to another workspace isn't refused. The same workspace with another token still is, as above.
- At a start offline, the workspace the user was in answers from its
copy: which one it was is kept beside the user's id
(
backend-scope:<server>, and the ones visited underbackend-scopes:<server>). - Signing out counts and drops every workspace's writes on that server,
and forgets every workspace's copy, not only the one it's in.
Account.pending(several servers) counts them all too. - No workspace in the user value (the path doesn't lead anywhere): it
behaves as without
offline_scope_path, copy dropped at a switch.
Signed in to more than one server
Some people work in more than one company's server: their employer's, and a
customer's. .multiple_servers() keeps them signed in to each, one of them
active, and moves between them without signing out
(RFC 0022):
App::new().backend(
Backend::chosen_at_sign_in()
.multiple_servers()
.user_route("/api/v1/me")
.broadcasting_from("/api/desktop/broadcasting")
.offline(),
)
let auth = ctx.get::<Auth>();
auth.sign_in_with_token("https://acme.example.com", &acme, acme_me).await?; // Acme active
auth.sign_in_with_token("https://kunde.example.com", &kunde, kunde_me).await?; // added, Kunde active
for account in auth.accounts() { // Account { server, user_id, user, active, pending, failed }
println!("{} {}", account.server, account.active);
}
auth.switch_to("https://acme.example.com").await?; // nothing revoked
auth.sign_out_of("https://kunde.example.com").await?; // Kunde's token revoked, Acme goes on
auth.sign_out_all().await?; // each revoked on its own server
- One account per server. Each has its own token
(
backend-token:<server>in the keychain), the user's id beside it (backend-user:<server>), its own offline copy and its own outbox. The list is underbackend-servers, the active one underbackend-server, and both outlive a restart. The user value is known per server for the run (Account.user), as given tosign_in_with_tokenor read while that server was active; at a start it'sNoneuntil the server is active andauth.user()reads it. - Signing in to another server adds it and makes it active. The others stay signed in, untouched. Signing in again to one already in the list replaces its token (another workspace there: the same rules as a switch).
switch_to(server)makes another one active. Requests go there with its token; the broadcaster reconnects there (its settings, its key, the channels named from its user, and the presence channels windows want); abilities are read again; everything live that read the backend re-runs; its outbox carries on.elyra:authis sent once,{ signedIn: true, user, server }. Nothing is revoked, and no copy is dropped.sign_out_of(server)revokes that server's token, there, and forgets it and its copy. The active one: the next in the list becomes active first, so the UI never shows "signed out". The last one is a sign-out as always.sign_out()issign_out_ofthe active server;sign_out_all()leaves every one, the active one last.- A
401signs out of that server alone, and the next one becomes active. elyra:accountscarries{ accounts, active, signedOutOf, reason }after each change:signedOutOfandreason("signed-out","expired") name a server just left.- Without
.multiple_servers()nothing changes: another server needs a sign-out first, andaccounts()lists the one signed in to, if any.
From the frontend:
import { accounts, auth, onSignedOutOf } from "@elyra/runtime";
$accounts.accounts; // [{ server, userId, user, active, pending, failed }]
await auth.switchTo("https://acme.example.com");
await auth.signOutOf("https://kunde.example.com"); // kind pending_changes while its writes wait
onSignedOutOf((server, reason) => toast(`Signed out of ${server}`));
The <AccountSwitcher> from @elyra/ui is all
of it in a menu: the servers, switching, and signing out, asking before it
drops changes that haven't been sent.
Signing in to a server stays the app's Rust code: a page can move between the servers the user signed in to, and leave them, never point a token at a new host.
Each account's outbox, counted. Account.pending and Account.failed
are that server's writes waiting and refused, whether it's active or not,
and elyra:accounts is sent again whenever they change. The
<AccountSwitcher> shows them under each server.
Offline, per server. Each server's reads are answered only from its own
copy, kept across switches. A write queued on one server is tagged with that
server and its user, and is sent only there, with that server's token: it
waits, untried, while another server is active, and goes when its own is
active again. The outbox, $outbox and $connection.pending are the active
server's. Signing out of a server with writes waiting is refused with
PendingChanges; sign_out_of_discarding(server) drops them, returns how
many, and dispatches OutboxDropped { server, count }.
A token per workspace
On some servers a token names one workspace: a user in three workspaces
holds three tokens. .token_per_workspace(..) says where the workspace is
in the user value, and Auth keeps every workspace's token and user beside
the others' on that server
(RFC 0031):
Backend::chosen_at_sign_in()
.multiple_servers()
.user_route("/api/v1/me") // { "user": { "id": 7 }, "workspace": { "id": 3, "name": "Support" } }
.user_id_path("user.id")
.token_per_workspace("workspace.id")
let auth = ctx.get::<Auth>();
for w in &approved.workspaces { // one sign-in per workspace,
auth.sign_in_with_token(&server, &w.token, me(&user, w)).await?; // the last one in use
}
auth.accounts()[0].workspaces; // [Workspace { id, user, active, pending, failed }]
auth.switch_workspace(&server, "12").await?; // nothing revoked
auth.sign_out_of_workspace(&server, "7").await?; // its token revoked, the rest go on
let unread: Inbox = auth.request_in(&server, "7", Method::Get, "/api/v1/inbox")?.json().await?;
- Kept per workspace: its token (
backend-token:<server>#<workspace>) and who the user is there (backend-workspace:<server>#<workspace>, the user value as given tosign_in_with_token), listed underbackend-workspaces:<server>. Unlike the server's user, they outlive a restart: at a start the user of the workspace in use is known before the server is asked, andAccount.workspaceslists every workspace with its user, for a switcher.backend-token:<server>stays the token in use. - The offline copy and the outbox are kept per workspace, as
offline_scope_pathkeeps them. switch_workspace(server, workspace)puts its token in use: a switch on the active server, nothing revoked; on another server, that server becomes active in that workspace.sign_out_of_workspace(server, workspace)revokes that token, with itself, and forgets it. The one in use: the server's next workspace takes its place. The server's last:sign_out_of(server). Refused withPendingChangeswhile its writes wait.sign_out_of(server)revokes every workspace's token there.- A
401ends the workspace whose token was refused: the server's next is in use,elyra:authsayssignedIn: trueonce, with its user, andelyra:accountsnames it insignedOutOfWorkspacewithreason: "expired". The server's last workspace: the server is signed out of, as without workspaces. request_in(server, workspace, method, path)asks a workspace that isn't in use, with its token. A401there signs nothing out: the app decides.- Another user signing in on the server forgets the workspaces of the one before.
update_user(user)keeps the user as the server describes them now (a profile changed) as the workspace's; readinguser_routeagain does too.
From the frontend, auth.switchWorkspace(server, workspace),
auth.signOutOfWorkspace(server, workspace), $accounts.accounts[i].workspaces
and onSignedOutOfWorkspace((server, workspace, reason) => …); signing in
to a workspace stays the app's Rust code.
Updates from the server. An app distributed from each customer's own
server, behind sign-in, asks that server for its updates:
UpdaterConfig::from_backend("/api/desktop/update", version) sends
GET /api/desktop/update?platform=…&version=… to the active server as the
signed-in user, and downloads the release only from that server's origin,
with the same token. Signed out, nothing is asked; after a switch, the new
active server is. Route::elyraUpdates() from elyracode/elyra-backend
serves it, from the releases php artisan elyra:release puts on a disk.
See the updater
(RFC 0024).
Live queries
A live command that reads from the backend updates itself when this app writes, and re-runs only what the write could have changed (RFC 0017):
a GET of |
depends on |
|---|---|
/api/customers?page=2 (a list) |
the resource's lists, backend:list:/api/customers |
/api/customers/count (a part of the list) |
the same lists |
/api/customers/42 (a record) |
that record, backend:/api/customers/42 |
/api/customers/12/notes (under a record) |
its own lists, and record 12 |
Every read also depends on its resource, backend:/api/customers, and
each path it's under. The resource is the path without its query and
trailing ids (a number, UUID or ULID).
- A write (
POST,PUT,PATCH,DELETE) re-runs the lists, and the record its path names.PUT /api/customers/40re-runs the lists and the view of customer 40, not customer 42's.POST /api/customersre-runs the lists.POST /api/customers/40/archiveis a change to customer 40. .with_lists()on a record'sGETmakes it re-run on every change to the resource. Use it for an endpoint that shows other records too.ctx.invalidate(&backend::resource_key("/api/customers"))re-runs every view of the resource.ctx.depends_on(&backend::list_key(..))re-runs on every change to it.ctx.depends_onandctx.invalidatecover paths that aren't shaped like anapiResource.LiveRegistry::stats()and the inspector say how often each query re-ran and how often its result changed.
As with the database, a live command's re-run may not write.
Changes made elsewhere, on the web or in a colleague's app, come in through broadcasting.
Broadcasting: changes made on the web
Laravel announces its changes with broadcasting, and the app listens the way Laravel Echo does in a browser (RFC 0006):
App::new().backend(
Backend::new("https://crm.example.com")
.broadcasting(Broadcasting::pusher("app-key")) // REVERB_APP_KEY
.follow("customers", "/api/customers"), // private-customers → re-run what read /api/customers
)
- The connection: the Pusher protocol, which Askr
(
--pusher), Reverb and Pusher speak. It goes to the backend's own host, as Askr serves it;.host(),.port()and.scheme("ws")point it at a Reverb on its own port. It'swssonly, except to loopback. - When: once the user is signed in, and it closes on sign-out. A dropped connection reconnects, backing off from 1 s up to 30 s, and then re-runs everything followed, since events sent meanwhile are lost.
- Private channels are authorized by the backend, as the signed-in user,
at
/api/broadcasting/auth. The app secret stays on the server. ->toOthers(): while connected,BackendsendsX-Socket-ID, so Laravel can skip the app whose own write already re-ran its queries.
Each event on a followed channel does three things:
- It re-runs the live queries it could have changed, coalesced, and
pushed only if the result changed. An event whose
modelnames its record (Laravel's model broadcasting:CustomerUpdated { model: { id: 40, … } }) re-runs the lists and the views of customer 40. Any other event re-runs everything that read the resource. A model whose route key isn'tidsays so:.record_key("/api/invoices", "uuid"). - It's a domain event,
BackendEvent { channel, event, data }:App::listen(|e: BackendEvent, ctx| …)for a notification or a log. - It reaches the windows on
elyra:backend:
import { onBackendEvent, broadcasting } from "@elyra/runtime";
onBackendEvent("customers", "CustomerUpdated", (data) => toast(`${data.model.name} was updated`));
// $broadcasting.state: "connecting" | "connected" | "offline"
The data is the server's, untrusted like any input. Re-running a query
doesn't read it, only the fact that something changed. .follow_public(..)
follows a public Channel; presence channels have their own section,
and so do private channels a window listens to.
On the Laravel side, the model announces itself and a channel rule says who may listen:
php artisan install:broadcasting --reverb # or Askr: `askr serve --pusher`
// app/Models/Customer.php
class Customer extends Model
{
use BroadcastsEvents;
public function broadcastOn(string $event): array
{
return [new PrivateChannel('customers')];
}
}
// routes/channels.php
Broadcast::channel('customers', fn ($user) => true);
// bootstrap/app.php — channel auth under /api, with the Sanctum token
->withBroadcasting(__DIR__.'/../routes/channels.php', [
'prefix' => 'api', 'middleware' => ['api', 'auth:sanctum'],
])
Events are queued by default. Run a queue worker, or set
QUEUE_CONNECTION=sync. For Askr, point Laravel's reverb connection at it
(REVERB_HOST, REVERB_PORT) with the same app key and secret.
Channels from the user
Laravel often broadcasts on channels named after the user, or the
workspace their token is for: private-user.7, private-workspace.3.
.follow(..) takes a fixed name. .follow_user(..) names the channel from
the signed-in user:
App::new().backend(
Backend::chosen_at_sign_in()
.user_route("/api/v1/me") // { "user": { "id": 7 }, "workspace": { "id": 3 }, … }
.revoke_route("/api/v1/token")
.user_id_path("user.id")
.broadcasting_from("/api/desktop/broadcasting") // { "key": "…", "host": "…", "port": 443 }
.follow_user("chat", "user.{user.id}", None) // private-user.7
.follow_user("workspace", "workspace.{workspace.id}", Some("/api/v1/issues")), // private-workspace.3
)
{dotted.path}is filled from the user value, assign_in_with_tokenwas given it oruser_routeanswered it: a string or a number. A placeholder the user doesn't have skips that channel, with a warning in the log. The others are still followed.- It's a private channel,
private-on the wire, authorized at the auth route as any other (Broadcasting::auth_route,/api/broadcasting/authby default). - It's named again at each connection, so after a switch the app listens on the new user's and workspace's channels, not the old ones.
- Its events are
BackendEvents on the follow's name, onelyra:backend, as for.follow(..). With a resource, they re-run what read it too.
import { onBackendEvent } from "@elyra/runtime";
onBackendEvent("chat", "MessagePosted", (data) => append(data.message));
onBackendEvent("workspace", null, () => refreshSidebar());
Who else is here: presence
Two people open the same customer, one in the browser and one in the desktop app. With Laravel's presence channels, each sees the other before either saves (RFC 0015):
Backend::new("https://crm.example.com")
.broadcasting(Broadcasting::pusher("app-key"))
.presence(["customers.*"]) // the channels a window may join
// routes/channels.php: the same rule Echo.join('customers.42') uses on the web
Broadcast::channel('customers.{id}', fn ($user, $id) =>
$user->can('view', Customer::find($id))
? ['id' => $user->id, 'name' => $user->name, 'avatar' => $user->avatar_url]
: false);
<Card title={record.name}>
{#snippet actions()}<Presence channel={`customers.${id}`} />{/snippet}
</Card>
- A window joins while something follows the channel:
<Presence>, or the runtime'spresence(channel)store ($here.members,$here.me,$here.joined). The app joins each channel once for all its windows, and leaves when the last one leaves, or closes. - The members are Laravel's: each one's
idand theinfoits channel rule returned. A user with two tabs is one member.<Presence>leaves the user out (selfshows them). - Only listed channels. A name
Backend::presence(..)doesn't cover is refused (denied) before anything is sent. Laravel's rule still decides who gets in; afalseleaves it unjoined, and the connection goes on. - Without a connection (signed out, offline, unplugged in the inspector), nothing is joined and nobody is shown. The channels are joined again when it's back.
- In Rust,
ctx.get::<Presence>()hasmembers(channel)andchannels(). make:resource --backend .. --presenceputs a<Presence>on the detail view and the edit form, and prints both lines above.
Who's editing
An edit form can say it's being edited, and show who else is:
<Presence channel={`customers.${id}`} editing={changed} />
Ada changes a field in the desktop app; Grete, with the same customer open in the browser, sees "Ada is editing" next to her avatar, and the other way round. It's a whisper on the presence channel, as Echo sends one, so the web half takes part with Echo alone:
// The browser: say it, and hear it.
const channel = Echo.join(`customers.${id}`);
channel.whisper("editing", { editing: true });
channel.listenForWhisper("editing", (e, { user_id }) => markEditing(user_id, e.editing));
- Information, not a lock. Laravel never sees a whisper. Two people can still both save; the conflict check at save time (RFC 0007) is what stops a lost update.
- When it's said. The app tells the channel when its first window
starts editing and when its last one stops (
editingback tofalse, or the form closing), not on each keystroke. Whispers aren't kept, so it says it again to someone who joins later, and after a reconnect. - Who said it. A member counts as editing only when the server names
them: Reverb adds the sender's
user_idto a whisper on a presence channel, and only from a member, with its defaultREVERB_APP_ACCEPT_CLIENT_EVENTS_FROM=members. Withall, it doesn't name the sender, and nobody shows as editing; withnone, whispers are refused. On Pusher, enable client events for the app. - Askr's
--pusherdoesn't pass whispers on (nor presence members). - The runtime has it as
presence(channel).editing(true), while the store is subscribed; each member hasediting. In Rust,Presence::editing(window, channel, on)andediting_here(channel). make:resource --presence's edit form passesediting={changed}: changed from the record as it was loaded.
Following a colleague
Two colleagues going through the overdue invoices on a call: one clicks the other's avatar, Follow, and their window goes where the other's goes, without sharing a screen (RFC 0042).
Backend::new(url)
.broadcasting(Broadcasting::pusher(key))
.presence(["office", "customers.*"]) // `office`: everyone in the app
// routes/channels.php: who's in the app, and what's shown of them
Broadcast::channel('office', fn ($user) => ['id' => $user->id, 'name' => $user->name]);
<Presence channel="office" follow />
- The leader is asked first, in their focused window: "Grete wants to follow you", Allow or Don't. Nothing of their route is sent before they allow it; no answer in a minute is a no.
- Only the route travels, as a whisper on the channel
(
client-route { route }): when it changes, and every 30 seconds while someone follows. The follower's window goes there as the follower, with their own token and abilities, and only to one of the app's own routes. - It ends when either presses Stop, the follower goes somewhere themselves, or either leaves the channel (closes the app, signs out, goes offline).
- Routes kept back:
following.share((route) => !route.startsWith("/settings")); the follower then sees "Ada is somewhere you can't follow" until she's back. - The runtime:
presence(channel).follow(id)(true once allowed),$following(whom this window follows, or null),$followers(who follows this user),following.stop(),following.stopFollowers(). In Rust,Presence::follow,unfollow,answer,stop_followers,route. - The whispers, for a web half with Echo:
client-follow-ask { to },client-follow-yes { to }/client-follow-no { to },client-follow-stop { to }andclient-route { route }, acted on only whentois the user and Reverb names a member as the sender. Askr's--pusherdoesn't pass whispers on.
A window listens: private channels per record
Laravel often broadcasts on a channel per record: an agent's run on
private-task.{ulid}, a model on private-App.Models.Task.{id}. The app
can't list those when it's built. A window listens to one while it shows
that record (RFC 0023), as it joins a
presence channel:
Backend::chosen_at_sign_in()
.broadcasting_from("/api/desktop/broadcasting")
.listen(["task.*"]) // the private channels a window may listen to
// routes/channels.php: the same rule Echo.private('task.01JD…') uses on the web
Broadcast::channel('task.{task}', fn ($user, Task $task) =>
$user->workspaces->contains($task->workspace_id));
<script>
import { listen, listening } from "@elyra/runtime";
let { run } = $props();
let output = $state("");
// listen(..) returns its unsubscribe: the effect's cleanup.
$effect(() => listen(`task.${run.id}`, (data, e) => {
if (e.event === "RunOutput") output += data.chunk;
}));
const live = $derived(listening(`task.${run.id}`));
</script>
{#if !$live.joined}<small>Not live</small>{/if}
- A window listens with the runtime's
listen(channel, handler), orlisten(channel, "RunOutput", handler)for one event; the handler gets(data, event), asonBackendEvent's does, andlistenreturns its unsubscribe. Thelistening(channel)store has$live.joinedand$live.last, the last event. The app subscribes to each channel once for all its windows and components, and unsubscribes when the last one stops, or its window closes. - Only listed channels. A name
Backend::listen(..)doesn't cover is refused (denied) before anything is sent.private-is added on the wire; don't write it. - Authorized as a follow is, at the broadcasting auth route, as the
signed-in user. Laravel's rule decides: a
false(its403) leaves the channel unjoined, logged, and the connection goes on. - Only the windows listening hear its events, on
elyra:backend, asBackendEvent { channel: "task.01JD…", event, data }. They aren't domain events, and re-run no live query.onBackendEvent("task.01JD…", ..)hears them too, in a window that listens. - Without a connection (signed out, offline, unplugged in the
inspector), nothing is joined, and
$live.joinedisfalse. A reconnect, another workspace's token and another server (a switch) each subscribe again, with that token and that server's auth. Events sent meanwhile are lost: whenjoinedcomes back, read what the window shows again. - In Rust,
ctx.get::<Listening>()haschannels(),joined(channel)andstate(channel).Capability::Listencovers the route; a window limited by RFC 0016 needs it.
Working offline
With no network, on a train or while the server is deployed, an app can keep showing what it last read (RFC 0007):
App::new()
.database("sqlite://app.db?mode=rwc") // where the copy lives
.backend(Backend::new("https://crm.example.com").offline())
- Reads: each successful
GETkeeps its answer, per user, URL and query. AGETthat gets no answer returns that copy instead of anofflineerror; one never read before is stilloffline. No command changes.Response::stale_since()says when the copy was made..no_offline()on a request keeps it out: a one-time code, a big report. - The connection state: no answer means offline. While offline, reads
answer from the copy at once, and Laravel's health route (
/up,.health_route(..)) is probed every 1 s, backing off to 30 s. Any answer, from the probe, any request or broadcasting reconnecting, means online again, and every live query that read from the backend re-runs. The state is onelyra:connection({ state: "online" | "offline", since }) andBackend::connection(). - Trying it: in a debug build, the inspector's
Simulate offline unplugs the backend without stopping Laravel; the
state then carries
simulated: true. - Whose copy: it's kept in
elyra_backend_cachein the app's database, created on first use, with the server, the user and the URL hashed. It's kept per user and per server, only while signed in, and cleared when the user signs out or someone else signs in. An expired sign-in keeps it for the same user. Signed in to several servers, each keeps its own; with.offline_scope_path(..), so does each workspace. It's capped at 100 MiB (.offline_cache_limit(..), oldest first), and an answer over 2 MiB isn't kept.
Writes: the outbox
A write marked .queue_offline() that gets no answer waits in the outbox
instead of failing:
#[command]
async fn customers_store(ctx: Ctx, input: CustomerInput) -> Result<Customer> {
let customer: Customer = ctx
.get::<Backend>()
.post("/api/customers")
.body(&input)
.queue_offline()
.resource()
.await?; // no answer: Err(BackendError::Queued(id)), kind "queued"
ctx.dispatch(CustomerCreated { customer: customer.clone() }).await?;
Ok(customer)
}
queuedis an error kind, not a value. The command's types stay what they are, and the code after the write runs only when the write really happened. The frontend gets kindqueuedand says "Saved, it will be sent when you're back online".- Sent in order, once. When the server is back, writes go one at a time,
oldest first, each with the
Idempotency-Keyit was first tried with. While earlier writes wait, a new one waits behind them, even online. Without.queue_offline()a write fails withofflineas before: a payment shouldn't go later by accident. - The server's answer, when it's sent:
- A
2xxdispatchesOutboxSent { id, method, path, status, body }, and the lists re-run. - A
422,403,404or another refusal moves the write aside, with the server's message and errors per field, and dispatchesOutboxFailed. The next writes go on. A404on aDELETEcounts as sent. - A
401waits, untried, until the same user signs in again. - No answer, a
5xxor a429is tried again with backoff (1 s up to 5 minutes, or the server'sRetry-After), and the rest wait behind it.
- A
Outbox(ctx.get::<Outbox>()):pending(),failed(),items(),retry(id, Some(fixed_body)),discard(id),flush(). The counts are onelyra:connectionaspendingandfailed.- Signing out with writes waiting or refused is refused with kind
pending_changes, since they'd be lost.Auth::sign_out_discarding()signs out anyway. - It's kept in
elyra_outboxandelyra_outbox_failed, per user, created on first use. It survives a restart, and the token is never stored there.
In the frontend
<script>
import { connection, outbox, auth } from "@elyra/runtime";
</script>
{#if $connection.state === "offline"}
<p>Offline since {new Date($connection.since).toLocaleTimeString()}
— {$connection.pending} change(s) waiting</p>
{/if}
{#each $outbox.filter((w) => w.status === "failed") as w}
<p>{w.method} {w.path}: {w.error}</p>
{#if w.reason === "conflict"}
<button on:click={() => outbox.keepMine(w.id)}>Keep mine</button>
<button on:click={() => outbox.takeTheirs(w.id)}>Take theirs</button>
{:else}
<button on:click={() => outbox.retry(w.id, fixedBody)}>Send again</button>
<button on:click={() => outbox.discard(w.id)}>Discard</button>
{/if}
{/each}
connectionis{ state, since, pending, failed }. It's alwaysonlinefor an app without.offline().outboxlists the writes, oldest first:{ id, method, path, body, status, attempts, error, errors, reason, createdAt }.errorsare per field, as aValidationErrorhas them.- A save that answers kind
queuedworked: "Saved, it will be sent when you're back online". auth.signOut()rejects with kindpending_changeswhile writes wait. Ask the user, thenauth.signOutDiscarding(). Signed in to several servers,auth.signOutOf(server)andauth.signOutOfDiscarding(server)do the same for one.
The page goes through /__auth/outbox (Capability::Auth). It can list,
retry, resolve and discard writes, and a retry may change the body only. It
can't add a write, change one's method or path, or see the token.
Conflicts
By default the last write wins, as in Laravel: Ada's update, sent once she's back online, overwrites what Bob changed meanwhile. Where that's wrong, a write carries a precondition:
backend.put(format!("/api/customers/{id}"))
.body(&input)
.unless_changed_since(&customer.updated_at) // If-Unmodified-Since
.queue_offline()
The server checks it and answers 412 when the record changed, and 409
means the same. Online, that's BackendError::Conflict, kind conflict.
From the outbox, the write is refused with reason: "conflict", and the user
chooses between two resolutions:
outbox.keep_mine(id)sends it again without the precondition.outbox.take_theirs(id)drops it and re-reads the record.
On the Laravel side it's one line in the controller:
abort_if($request->hasHeader('If-Unmodified-Since')
&& $customer->updated_at->gt(Carbon::parse($request->header('If-Unmodified-Since'))), 412,
'Someone changed this customer meanwhile.');
Shown at once
A write marked .optimistic() shows in every window before the server
answers (RFC 0039):
#[command(can = "customers.update")]
async fn customers_update(ctx: Ctx, id: i64, input: CustomerInput) -> Result<Customer> {
Ok(ctx.get::<Backend>()
.put(format!("/api/customers/{id}"))
.body(&input)
.optimistic()
.queue_offline()
.resource()
.await?)
}
- For a
PUT,PATCHorDELETEto a record (/api/customers/42,/api/customers/42/notes/7). APOSTthat creates one isn't: where it goes in a sorted, filtered list is the server's to say. - At once. When the command sends it, the live queries that read the
record or its lists re-run from the offline copy with the write applied,
without asking the server. It needs
.offline(): without the copy, the change shows when the server answers (and the log says so once). - Applied to every read of that record and its lists while it's on its
way or waits in the outbox, from the server or from the copy, so a
re-read doesn't flicker back: the record's fields (in
datatoo), the item in a list (matched by its key,.record_key(..)if it's another), aDELETEtaking the item out andtotaldown by one. Only the fields the record already has change:passwordisn't added,updated_atstays the server's. When the body isn't the record's shape,.optimistic_with(&fields)says what changes. - Yes from the server: the lists re-run from the server, as after any
write. No (
422,403,404,409,412): it's no longer applied, and every window shows the record as the server has it; the error is the command's, or the outbox's. No answer, with.queue_offline(): it waits in the outbox and stays shown, across a restart, until it's sent or refused. - The offline copy stays what the server said: a write is applied when a read is answered, never stored.
make:resource --backend generates it on the update (.optimistic_with(&input))
and delete commands. In the frontend, $pending says which records have a
change not yet sent, per resource path:
<script>
import { pending } from "@elyra/runtime";
</script>
<!-- { customers: [42], "customers/42/notes": [7] } -->
<Table page={customers} bind:query columns={["name"]} pending={$pending.customers} />
<Table pending> puts a small dot on those rows, "Not sent yet"
(Table).
Idempotency on the Laravel side
A middleware answers a repeated key from its record, so a write that reached
the server before the connection dropped isn't made twice. It goes after
auth:sanctum, so it knows whose key it is, and it remembers only writes that
happened. A refused write sent again (fixed, or "keep mine") carries a new key
anyway:
// routes/api.php
Route::middleware(['auth:sanctum', Idempotent::class])->group(function () { /* … */ });
// app/Http/Middleware/Idempotent.php: a write that happened, answered again for 24 h per key and user
public function handle(Request $request, Closure $next)
{
$key = $request->header('Idempotency-Key');
if (! $key || $request->isMethodSafe()) {
return $next($request);
}
$cacheKey = 'idempotency:'.$request->user()?->id.':'.$key;
if ($seen = Cache::get($cacheKey)) {
return response($seen['body'], $seen['status'], ['Content-Type' => 'application/json']);
}
$response = $next($request);
if ($response->isSuccessful()) {
Cache::put($cacheKey, ['status' => $response->getStatusCode(), 'body' => $response->getContent()], now()->addDay());
}
return $response;
}
Laravel's notifications
What $user->notify(..) sends through the database and broadcast
channels reaches the desktop: a notification in the OS, the unread count on
the app's icon, and a list in the app, read once wherever the user reads it
(RFC 0008):
App::new().backend(
Backend::new("https://crm.example.com")
.broadcasting(Broadcasting::pusher(key))
.notifications(), // App.Models.User.{id}, and /api/notifications
)
class InvoicePaid extends Notification
{
public function via(object $notifiable): array
{
return ['database', 'broadcast'];
}
public function toArray(object $notifiable): array
{
return ['title' => 'Invoice paid', 'body' => "Invoice 7 was paid.", 'url' => '/invoices/7'];
}
}
- Heard on the signed-in user's private channel, Laravel's
App.Models.User.{id}(.notifications_channel(..)for another), authorized by the backend like any private channel. Signing in as someone else follows theirs. Each one is aNotificationReceived(a domain event with theNotificationand how it'sPresented) and is sent to the windows onelyra:notification. It needs.broadcasting(..), and the app won't start without it. - Shown:
title,bodyandurlfrom whattoArrayreturned, by convention, or.present_notifications(|n| Presented { .. }). With no window of the app in front, the OS shows it (thesystemfeature; on macOS a bundled app). With one in front, it's for the app to toast (e.shown === "toast")..notification_previews(false)shows only "New notification", for a locked screen. - Clicked: the app comes forward, the notification is read, and its
urlopens when it's a path in the app (/invoices/7). A full URL is never opened by a click. The app's own listener can open one: it's aNotificationClicked, also onelyra:notification-clicked. - Counted: the unread count, the server's, is on the dock (macOS), the
launcher (Linux), or the taskbar button (Windows), and on the tray
(beside its icon, or a dot on it).
.notification_badge(false)turns that off, and signing out clears it. - Listed and read:
Notifications::refresh()readsGET /api/notifications, Laravel's paginator withunreadbeside it, andmore()reads the next page.mark_read(id)andmark_all_read()count down at once and post to/{id}/readand/read-all, through the outbox when offline. What was read here stays read until the server shows it read too. The list is read again when a window gets focus, and when the web broadcastsNotificationsRead. - Missed while offline or closed: when the connection is back, or at the
start, what came meanwhile is shown, one as itself, more as "4 new
notifications" that opens
/notifications. A user's first sign-in on a machine shows nothing. The newest one listed is kept in theStore.
The Laravel side is the notifications table (php artisan make:notifications-table), a NotificationController with index, read
and readAll, its routes under auth:sanctum, and a NotificationsRead
event broadcast ->toOthers() when the web reads them. rata make:notifications prints all of it; scripts/laravel-backend.sh has it
working.
In the frontend:
<script>
import { notifications, onNotification, toast } from "@elyra/runtime";
onNotification((e) => e.shown === "toast" && toast(e.presented.title));
</script>
<a href="#/notifications">Notifications {$notifications.unread}</a>
{#each $notifications.items as n (n.id)}
<button onclick={() => notifications.markRead(n.id)}>{n.data.title}</button>
{/each}
Or the <NotificationBell> from @elyra/ui:
the unread count on a bell, and the newest in a panel beside it.
The notifications store ({ unread, items, hasMore }) is read from the
server when first subscribed, then kept up to date, with refresh(),
more(), markRead(id) and markAllRead(). While it's subscribed, a click
on a notification in the OS opens its path in the app. onNotificationClicked
hands a click to the app. It all goes through /__auth/notifications*
(Capability::Auth): the page may read the list and mark it read, nothing
else.
rata make:notifications
It writes app/src/resources/notifications/ and lists it in the resource
registry:
- the page at
#/notifications, with Mark all read, More, and the offline banner; - a nav item with the unread count.
rata newrenders a nav item'scountsince 0.15, and rata prints the lines for an olderApp.svelte; - toasts while the app is in front, and the click that opens a page, set up once for the whole app.
It prints the Laravel side, and the .notifications() hint until main.rs
has it.
What the user may do
Laravel decides what each user may do: a policy, a Gate, or
spatie/laravel-permission's roles. .abilities() brings that list to the
desktop (RFC 0010):
App::new().backend(Backend::new(url).abilities()) // GET /api/abilities
let abilities = ctx.get::<Abilities>();
if abilities.allows("customers.export") { /* … */ }
- After sign-in the app reads
GET /api/abilitiesas the user: a list of strings (["customers.view", "invoices.*"], a trailing*covering a namespace), or the same inside{ "data": … }. Signing out forgets it. - Before the list has been read, and signed out, the user has none.
- With
.offline(), the list is part of the user's offline copy, so it holds while the server can't be reached.
The list stays current. It's read again when a window gets focus and when
the connection comes back, and at once when Laravel broadcasts
AbilitiesChanged on the user's private channel (App.Models.User.{id},
followed with .broadcasting(..) whether or not notifications are on):
// elyracode/elyra-backend does this for spatie's role and permission events
// (with `permission.events_enabled`); for anything else:
broadcast(new \Elyra\Backend\Events\AbilitiesChanged($user));
A live command that asks abilities.allows(..) re-runs when the list
changes.
In the frontend, $can(..) hides what the user can't do:
<script>
import { can, abilities } from "@elyra/runtime";
</script>
{#if $can("customers.delete")}
<button onclick={remove}>Delete</button>
{/if}
$can is false until the list is read and while signed out; $abilities
is the list itself ({ loaded, abilities }), and abilities.refresh() reads
it again. The page can read the list and ask for it again
(/__auth/abilities, Capability::Auth), never set it. An app without
.abilities() answers ["*"]: its own grants are all there is, and the
shell enforces them.
A command with #[command(can = "customers.delete")] then runs from the
frontend only when the app grants the ability (allow_ability, as always)
and the user has it. Otherwise it's refused at once with kind denied,
the kind Laravel's 403 has, without a request, and, offline, without being
queued to fail later. The app's own missing grant stays forbidden. Rust
callers (jobs, providers, TestApp::invoke) aren't gated.
// routes/api.php (elyracode/elyra-backend), inside auth:sanctum
Route::elyraAbilities(); // GET /api/abilities
Route::elyraAbilities() answers the user's spatie/laravel-permission
permissions (their roles' included) when the package is installed, and
otherwise every ability in config('elyra.abilities') the Gate allows them
(php artisan vendor:publish --tag=elyra-config). Any route that answers a
list of strings works too.
Per record, Laravel's policies can say more than a flat list: an API
Resource may add can, which the generated views prefer:
'can' => [
'update' => $request->user()->can('update', $this->resource),
'delete' => $request->user()->can('delete', $this->resource),
],
The app's assistant
An app with an assistant (RFC 0011) reaches Claude through Laravel, so no key is in the app. Laravel adds its key and decides what may be asked:
App::new()
.backend(Backend::new(url).abilities().assistant()) // POST /api/elyra/assistant/v1/messages
.assistant(Assistant::new().allow_abilities(["customers.*"]))
// routes/api.php (elyracode/elyra-backend), inside auth:sanctum
Route::elyraAssistant();
ANTHROPIC_API_KEY=sk-ant-…
# optional
ELYRA_ASSISTANT_MAX_TOKENS=4096
ELYRA_ASSISTANT_PER_MINUTE=30
ELYRA_ASSISTANT_STREAM=true
ELYRA_ASSISTANT_CODE_EXECUTION=false
ELYRA_ASSISTANT_WEB_SEARCH=false
- The desktop sends the Messages API's body with the user's Sanctum token. Signed out, the assistant can't be used ("Sign in to use the assistant.").
- Laravel answers only for the models in
config('elyra.assistant.models')(claude-sonnet-5-5by default), lowersmax_tokensto its cap, refuses Claude's own server tools, and allowsper_minuterequests per user. WithELYRA_ASSISTANT_CODE_EXECUTION=trueit passes code execution, for the assistant's code mode (RFC 0027): the server's owner decides that the results of code's calls may go through Anthropic's sandbox, kept up to 30 days, outside zero data retention. WithELYRA_ASSISTANT_WEB_SEARCH=trueit passes web search, for the assistant's web search: what the user asks goes into Anthropic's search. A refusal is the Messages API's error shape, which the desktop shows. The tool loop stays on the desktop: its tools are the app's commands. - Streaming (RFC 0018): a
request with
stream: trueis passed through as Claude writes it, astext/event-streamwithX-Accel-Buffering: no, so nginx doesn't hold it. The usage is read off the stream forAssistantUsed. A server that buffers anyway (a proxy in front, a PHP server that doesn't flush) can setELYRA_ASSISTANT_STREAM=false: the desktop then asks for each answer whole. Askr (1.9.2) holds a streamed response until it's done: the answer arrives right, but at once. SetELYRA_ASSISTANT_STREAM=falsethere until it passes streams on. - Each answered request dispatches
Elyra\Backend\Events\AssistantUsed(the user, the model and the tokens, never the prompt), to keep a record of who used how much. .assistant_route(..)moves the route.
Without .assistant(), the assistant uses the user's own key from the
keychain (/__assistant/key keeps it, write-only, with SecretsProvider),
and then the container's elyra::ai::Ai (AiProvider, from
ANTHROPIC_API_KEY). /__assistant/source says which is in use.
Speech to text
What the user says into the microphone becomes text through Laravel, so no key is in the app (RFC 0032):
App::new()
.microphone("Notes uses the microphone to let you dictate.")
.backend(Backend::new(url).transcription()) // POST /api/elyra/transcription/v1/audio/transcriptions
// routes/api.php (elyracode/elyra-backend), inside auth:sanctum
Route::elyraTranscription();
OPENAI_API_KEY=sk-…
# optional
ELYRA_TRANSCRIPTION_MAX_KB=25600
ELYRA_TRANSCRIPTION_PER_MINUTE=20
- The desktop sends OpenAI's transcription request (multipart:
file,model,language) with the user's Sanctum token. Laravel passes it on with its key, and the answer back as it came. - Laravel answers only for the models in
config('elyra.transcription.models')(whisper-1,gpt-4o-transcribe,gpt-4o-mini-transcribe), files up tomax_kb, andper_minuterequests per user. A refusal is OpenAI's error shape. - Each answered request dispatches
Elyra\Backend\Events\TranscriptionUsed(the user, the model and the file's size, never the audio or the text). .transcription_route(..)moves the route.
Files
Attach a file the user chose, and Laravel gets it as an upload (RFC 0009):
use elyra::files::ChosenFile;
#[command(can = "customers.update")]
async fn customers_attach(ctx: Ctx, id: i64, file: ChosenFile) -> elyra::Result<Attachment> {
Ok(ctx.get::<Backend>()
.post(format!("/api/customers/{id}/attachments"))
.attach("file", &file) // streamed from disk
.field("note", "Signed copy")
.max_size(20 * 1024 * 1024) // optional: refused here, before sending
.json()
.await?)
}
const [file] = await dialog.open({ filters: [{ name: "PDF", extensions: ["pdf"] }] });
if (file) await commands.customersAttach({ id: 7, file });
public function store(Request $request, Customer $customer)
{
$request->validate(['file' => ['required', 'file', 'mimes:pdf', 'max:20480']]);
return $customer->attachments()->create([
'path' => $request->file('file')->store('attachments'),
'name' => $request->file('file')->getClientOriginalName(),
]);
}
- A
ChosenFileis what the frontend hands over from a dialog or a drop (a file the user chose); Rust code can attach any path it knows, or bytes with.attach_bytes(..). - Laravel's
422on the file (mimes,max) is a validation error on its field, like any other. A413, from nginx'sclient_max_body_sizeor PHP'spost_max_sizebefore Laravel sees the request, is one too: "The file is too large for the server." PUT,PATCHandDELETEwith a file are sent as aPOSTwith_method, because PHP reads files only from aPOST. Laravel routes it as the method named.- Retries:
.idempotent()adds anIdempotency-Key(theIdempotentmiddleware honours it), so.retry(..)may send it again; the file is read again from the start. - The timeout is the time without progress, 30 s unless
.timeout(..)says otherwise: a large file on a slow line isn't cut off while it moves.
Downloads go to disk, never all into memory:
// To where the user chose in a save dialog (a ChosenFile of kind `save`):
let saved = backend.get(format!("/api/invoices/{id}/pdf")).download_to(&to).await?;
// Into a folder the user chose (kind `folder`), under the server's name:
let saved = backend.get("/api/exports/42").download_into(&folder).await?;
// Into the Downloads folder:
let saved = backend.get("/api/exports/42").download().await?;
// A signed URL the API returned (S3's temporaryUrl), fetched without the token:
let saved = backend.download_url(url).download_into(&folder).await?;
Route::get('/invoices/{invoice}/pdf', fn (Invoice $invoice) =>
Storage::download($invoice->pdf_path, "Invoice {$invoice->number}.pdf"));
- The name comes from
Content-Disposition(whatStorage::download's second argument sets), cleaned: it can't leave the folder, isn't hidden, and is numbered when taken (Invoice 7 (1).pdf). - A download is written to a
.partfile and renamed when complete. It's marked as downloaded from the internet (quarantine on macOS, the Mark of the Web on Windows), so the OS checks it before it's opened. Nothing is opened by itself. download_toneeds aChosenFilefrom a save dialog, anddownload_intoone of a folder: a file the user picked to read isn't overwritten.- A download isn't kept as the offline copy.
Uploads while offline
.queue_offline() works for an upload too. With no answer, it waits in the
outbox with a copy of its files, in the app's data
folder (elyra-outbox-files), so what's sent later is what the user
attached, even if they move, change or delete the original meanwhile:
backend.post(format!("/api/customers/{id}/attachments"))
.attach("file", &file)
.queue_offline()
.json()
.await?; // offline: Err, kind `queued`, and it's sent once the server is back
- It's sent once, with its
Idempotency-Key, in order with the other writes, and its copy is removed when it's sent or discarded. A refused one keeps its copy until it's retried or discarded; it's retried as it was (attach the file again to change it). Backend::offline_upload_limit(bytes)caps the copies a user's queued uploads may keep (500 MB by default). Over it, the upload isn't kept: it's theofflineerror instead.Backend::offline_upload_folder(path)puts them elsewhere.- The copies are per user, and go with the outbox when the user signs out discarding their changes.
transferslists a waiting upload asqueued; cancelling it takes it out of the outbox. The outbox's list shows its fields and each file by name.
Transfers
Every upload and download is in Transfers while it runs, and for a minute
after: its name (or .label(..)), how many bytes so far, the total, and
whether it's running, done, failed or cancelled. It's published on
elyra:transfers. Transfers::cancel(id) stops one: the command that
started it gets an error of kind cancelled, and a download leaves no
.part file behind.
let transfers = ctx.get::<Transfers>();
for t in transfers.list() {
println!("{} {}/{:?} {:?}", t.name, t.sent, t.total, t.state);
}
In the frontend it's the transfers store:
<script>
import { transfers } from "@elyra/runtime";
</script>
{#each $transfers.filter((t) => t.state === "running" || t.state === "queued") as t (t.id)}
<div class="transfer">
{t.direction === "upload" ? "↑" : "↓"} {t.name}
{#if t.state === "queued"}waiting for the network{:else if t.total}{Math.round((t.sent / t.total) * 100)} %{/if}
<button onclick={() => transfers.cancel(t.id)}>Cancel</button>
</div>
{/each}
The page can list transfers and cancel one (through /__auth/transfers, so
with Capability::Auth), nothing else.
Edit it in its own app
A file on a record (the contract, the budget, the drawing) can be opened in
the user's own app for it, Excel, Word, Preview, and sent back each time
they save (RFC 0038). Needs the
system feature beside backend.
#[command(can = "attachments.update")]
async fn attachments_edit(ctx: Ctx, id: i64) -> elyra::Result<Editing> {
Ok(ctx.get::<Backend>()
.edit(format!("/api/attachments/{id}/file")) // downloaded, opened in its app
.only(["docx", "xlsx", "pdf"]) // optional
.open()
.await?)
}
.open()downloads the file into a folder of the app's own (editingin its data folder;Backend::editing_folder(..)for another), one per server and user, under the server's name, so the editor's title bar shows "Contract Acme.docx". Then it's opened with the OS's default app for it. Opening the same file again opens the copy that's there, with whatever is unsaved in it.- A save is noticed once a second (the file's size and modified time),
sent once the file is still, and only if its content changed: an editor
that touches the file without changing it sends nothing. It's a
PUTto the same path, as aPOSTwith_method(PHP takes a file only with aPOST), the file asfile..save_back(path)sends it elsewhere,.save_back_with(Method::Post, path)as aPOST, for a server that keeps each save as a version. - Checked against its version. The download's
Last-Modified(or itsETag) is sent with the save asIf-Unmodified-Since(orIf-Match), and the save's answer moves it on:Last-Modified, theETag, orupdated_atin its JSON. Someone else's change meanwhile is a412, and the editing a conflict: keep mine sends it again without the check; take theirs downloads the server's version beside the user's file ("Contract Acme (from the server).docx") and opens it, never over a file that may be open in Word. Further saves wait behind a conflict. - No answer, and it waits. Only the last save waits, and it's tried again
every 15 seconds. The editing is its own outbox: it works without
Backend::offline(). - Signing out is refused (
pending_changes) while a save hasn't reached the server, as for the outbox;sign_out_discarding()drops it. Once signed out, every editing of that server ends and its folder goes. - An editing outlives the app. It's kept beside its file, and a file saved while the app wasn't running is sent at the next start, checked against its version. One with no change for seven days, and nothing waiting, ends at the start after.
Never a program: a file whose name is executable (.exe, .app, .sh, …,
as shell.openExternal refuses) or opens something else (.lnk, .url,
.webloc, .html, .svg, …) is refused before it's opened, and
.only([..]) narrows it to the kinds the app knows. The download is marked
as one, as every download is: on Windows, Office opens it in Protected View
and the user presses Enable Editing once.
On the Laravel side, the GET answers with the file (Storage::download
and response()->file(..); ->setLastModified($model->updated_at) gives
the version), and the PUT checks it. elyracode/elyra-backend has a
trait for the check:
use Elyra\Backend\Concerns\ChecksUnmodifiedSince;
class Attachment extends Model
{
use ChecksUnmodifiedSince;
}
Route::put('/attachments/{attachment}/file', function (Request $request, Attachment $attachment) {
abort_if($attachment->changedSince($request), 412, 'Someone changed it meanwhile.');
$request->validate(['file' => ['required', 'file', 'max:51200']]);
$attachment->replaceFile($request->file('file'));
return response()->json($attachment)->setLastModified($attachment->updated_at);
});
In the frontend, the editing store lists them, and the page acts on one
by its id, never a path:
<script>
import { editing } from "@elyra/runtime";
</script>
{#each $editing as e (e.id)}
<div class="editing">
{e.name}
{#if e.state === "saved"}saved {new Date(e.savedAt).toLocaleTimeString()}
{:else if e.state === "waiting"}waiting: {e.error}
{:else if e.state === "conflict"}
changed on the server too
<button onclick={() => editing.keepMine(e.id)}>Keep mine</button>
<button onclick={() => editing.takeTheirs(e.id)}>Take theirs</button>
{/if}
<button onclick={() => editing.show(e.id)}>Open</button>
<button onclick={() => editing.finish(e.id)}>Done</button>
</div>
{/each}
editing.reveal(id) shows its folder in Finder or Explorer. In Rust it's
Editings in the container: list(), show, reveal, finish,
keep_mine, take_theirs, and path(id) for the app's own tests.
make:resource --backend
rata make:resource Customer --backend /api/customers --generate name:string email:email 'phone:string?'
It makes the same resource as --generate, with the same screens, types,
abilities and events. The difference is that its commands call the API:
indexsendssearch,filters(a typedCustomerFilters, as PHP reads it),sort,direction,pageandper_pageas the query; the controller answers it withelyraList.show,store,updateanddestroyare one request each.
The model is a plain serde struct, with Laravel's ISO timestamps. There's no
migration or seeder, because the table is the server's. Validation is the
server's too: a 422 lands in the form, per field. The tests run against an
HttpFake.
The resource follows its channel. Its mod.rs has
FOLLOWS = &[("customers", commands::PATH)], the registry gathers them all,
and the app listens with
.broadcasting(Broadcasting::pusher(key)).follow_all(resources::follows()) on
its Backend. A generated test broadcasts through a PusherFake and watches
the open list re-run.
It works offline once the app has .offline(), and rata's hint says so:
- Its reads need nothing.
store,updateanddestroyare marked.queue_offline().outbox_sentdispatches the resource'sCreated,UpdatedorDeletedevent once a write saved offline reaches the server. The registry gathers them, and the app wires it once with.listen(resources::outbox_sent).- The list shows an offline banner and the writes waiting, and those the
server refused, with Fix, Keep mine / Take theirs and Discard. The form
opens a refused write with the server's errors, and says "Saved, it will be
sent" for kind
queued. - A generated test saves with no network and checks it's sent once, with its key.
With abilities on (the default), make:resource --backend generates a list
and a detail view that hide New, Edit and Delete when $can("<plural>.create")
and the others say no, preferring a record's can.update / can.delete
when the API sends it. rata prints the permissions to create and
Route::elyraAbilities().
A file field
rata make:resource Customer --backend /api/customers --generate name:string 'contract:file?'
A file field is a file on the server (files):
- The record has its name (
contract: Option<String>), what the API answers. storeandupdatetakecontract: Option<ChosenFile>beside the input. With a file, the input goes as a form with the file beside it (multipart); without, as JSON, as before. An update with a file is sent as aPOSTwith_method=PUT. Offline, it waits in the outbox with a copy.customers_contract(id, to)downloads it to where the user chose in a save dialog.- The form has
@elyra/ui'sFileFieldin aField: a button that opens the file dialog, and the first one takes a file dropped on the window. Laravel's message for the file shows under it. The detail view's file name downloads it. (Before 0.23, rata wrote anapp/src/resources/FileField.svelte; a form generated then keeps using it.) - rata prints the controller's lines (
$request->file('contract')->store(..), keeping the name and where it's stored) and the download route (Storage::download(..)).
The app needs elyra's system feature for the dialogs; rata says so.
rata prints what the Laravel side needs: Route::apiResource, the
BroadcastsEvents model and channel rule above, and the idempotency
middleware. The CustomerController in
scripts/laravel-backend.sh shows an index that reads that query. For now the project needs the database feature too,
because the resource registry also lists migrations.
The two halves, checked
The desktop app's types and the Laravel API drift apart without anyone
noticing until a user's list fails to decode. php artisan elyra:contract
describes the API (routes, FormRequest rules, abilities, and each read's
answer sampled as a user), and rata check --backend compares the app with
it (RFC 0040): a route a command
calls that isn't there, a field its type needs that isn't sent or comes as
null, an input field the rules require. See
the CLI.
Testing
use elyra::auth::MemoryTokens;
use elyra::http::{Http, HttpFake, Method};
let fake = HttpFake::new()
.get("https://crm.test/api/customers", 200, json!({ "data": [], "total": 0, "per_page": 25, "current_page": 1, "last_page": 1 }))
.post("https://crm.test/api/customers", 422, json!({ "errors": { "email": ["Taken."] } }));
let app = TestApp::new(
App::new()
.backend(Backend::new("https://crm.test"))
.token_store(Arc::new(MemoryTokens::new().with("backend-token:https://crm.test", "1|token"))) // signed in
.commands(commands())
.swap(Http::fake(fake.clone())),
);
let errors = app.invoke_validation_errors("customers_store", (input,)).await.unwrap();
fake.assert_sent("POST", "https://crm.test/api/customers");
TestApp keeps tokens in memory unless told otherwise, so a test never
touches the keychain. MemoryTokens::failing() behaves like a system without
one. Secrets is a token store too: .token_store(Arc::new(secrets.clone()))
with Secrets::fake() keeps each server's token where a test can read it.
One HttpFake answers any number of servers, by their full URLs, so two
servers signed in at once are tested as one
(framework/tests/multiple_servers.rs).
PusherFake stands in for Reverb or Askr. Point the backend at it with
.broadcasting(pusher.config()), then broadcast:
let pusher = PusherFake::start().await;
// …an app with `.broadcasting(pusher.config()).follow("customers", "/api/customers")`, signed in…
pusher.wait_for_subscriptions(1).await;
pusher.broadcast("private-customers", "CustomerCreated", json!({ "model": { "id": 4 } }));
list.next().await; // re-ran
Offline, the backend needs a database for its copy and its outbox. A route
marked unreachable is a network that's gone, and a later route for the same
URL brings it back:
let fake = HttpFake::new()
.post("https://crm.test/api/sanctum/token", 200, json!("1|token"))
.get("https://crm.test/api/user", 200, json!({ "id": 1 }))
.unreachable(Method::Post, "https://crm.test/api/customers")
.unreachable(Method::Get, "https://crm.test/up");
// …an app with `.bind(db)`, `.backend(Backend::new("https://crm.test").offline())`
// and `.swap(Http::fake(fake.clone()))`, signed in with `Auth::sign_in`…
assert_eq!(app.invoke_err_kind("customers_store", (input,)).await.as_deref(), Some("queued"));
fake.clone().post("https://crm.test/api/customers", 201, json!({ "data": { "id": 7 } }));
app.get::<Outbox>().flush().await;
assert!(app.get::<Outbox>().items().await.is_empty()); // sent
make:resource --backend generates this test for each resource.
A notification is a broadcast on the user's channel. Notifier::fake()
stands in for the OS's notification center:
// …an app with `.broadcasting(pusher.config()).notifications()`, signed in as user 1,
// and `.swap(Notifier::fake()).swap(Store::fake())`…
pusher.broadcast(
"private-App.Models.User.1",
"Illuminate\\Notifications\\Events\\BroadcastNotificationCreated",
json!({ "id": "9b1", "type": "invoice-paid", "title": "Invoice paid", "url": "/invoices/7" }),
);
app.get::<Notifier>().assert_shown(|n| n.title == "Invoice paid");
app.get::<Notifier>().click(0); // as the user would
scripts/laravel-backend.sh builds an app with
all of it. CI runs Elyra against it offline too, through a proxy the test
pulls the plug on.
Against a real Laravel app:
scripts/laravel-backend.sh /tmp/api
# Reverb too: the customers broadcast their changes, so writes need it
(cd /tmp/api && php artisan serve --port 8765 & php artisan reverb:start --port 8080 &)
ELYRA_LARAVEL_URL=http://127.0.0.1:8765 cargo test -p elyra --features backend --test laravel_backend
# Broadcasting, through Reverb (or Askr's --pusher) with the app's key
ELYRA_LARAVEL_URL=http://127.0.0.1:8765 ELYRA_PUSHER="$(grep ^REVERB_APP_KEY= /tmp/api/.env | cut -d= -f2)@127.0.0.1:8080" \
cargo test -p elyra --features backend,database --test laravel_broadcasting
# Working offline: a proxy the test pulls the plug on
ELYRA_LARAVEL_URL=http://127.0.0.1:8765 cargo test -p elyra --features backend,database --test laravel_offline
# Notifications, through Reverb
ELYRA_LARAVEL_URL=http://127.0.0.1:8765 ELYRA_PUSHER="…@127.0.0.1:8080" \
cargo test -p elyra --features backend --test laravel_notifications
CI runs all four, broadcasting through Reverb and then through Askr.
Related
- HTTP client · Live queries · Events · Resources · Secrets · Security