Merge main into feat/request-versioning

Conflicts were all at registration points; both sides are kept.

Main now routes every write through one connection (#642): ClientDb only
reads and writes go through `with_tx` on a WriteDb. Versioning follows:
snapshot, restore, prune and the cascade delete move to WriteDb, while the
lookups and the "has it changed" check stay on ClientDb. Callers take a
write transaction the way their neighbours do:

- The HTTP send snapshots in its own transaction from
  `resolve_send_inputs`, and a failure there (including not getting the
  writer) is still logged and swallowed, so the response just has no
  version.
- gRPC and WebSocket connect snapshot inside the transaction that upserts
  the connection.
- The snapshot and restore RPCs, on the desktop and in the browser host,
  each run in a transaction.
- The request and workspace cascades live on main's WriteDb deletes.

The Request Changed dropdown moves into the response pane's
`statusLineRight` slot, since main moved the status line into the shared
pane view.

The plugin runtime's copy of the model bindings picks up `versionId`, and
`gen_rpc.ts` is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and Stetta task tk_mw563e1dcqtc4sqh committed 2026-11-06 09:23:32 -07:00
commit 1b0a196c50
794 files changed
+76953 -18061

No files matched your search

+6 -6
View File
@@ -13,11 +13,11 @@
"@yaakapp-internal/rpc-schema": "^1.0.0",
"@yaakapp-internal/web": "^1.0.0",
"@yaakapp-internal/wasm": "^1.0.0",
"@tauri-apps/api": "^2.11.0",
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-fs": "^2.5.1",
"@tauri-apps/plugin-opener": "^2.5.4",
"@tauri-apps/plugin-os": "^2.3.2"
"@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-clipboard-manager": "^2.5.0",
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-fs": "^2.7.1",
"@tauri-apps/plugin-opener": "^2.7.2",
"@tauri-apps/plugin-os": "^2.4.0"
}
}
+3
View File
@@ -34,6 +34,9 @@ function host(): Platform {
* and cannot be made to wait.
*/
export const platform: Platform = {
get httpProxyUrl() {
return host().httpProxyUrl;
},
get capabilities() {
return host().capabilities;
},
+29 -2
View File
@@ -4,7 +4,7 @@ import { emit as tauriEmit, listen as tauriListen } from "@tauri-apps/api/event"
import { basename, resolveResource } from "@tauri-apps/api/path";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { clear, readText, writeText } from "@tauri-apps/plugin-clipboard-manager";
import { open, save } from "@tauri-apps/plugin-dialog";
import { open, save as saveDialog } from "@tauri-apps/plugin-dialog";
import { readDir, readFile, readTextFile } from "@tauri-apps/plugin-fs";
import { openUrl, revealItemInDir } from "@tauri-apps/plugin-opener";
import { type as osType } from "@tauri-apps/plugin-os";
@@ -67,6 +67,7 @@ const ALL_CAPABILITIES: PlatformCapabilities = {
clipboardRead: true,
systemFonts: true,
license: true,
agents: true,
};
function createWindow(): PlatformWindow {
@@ -119,11 +120,25 @@ function storedBodyPath(id: string): Promise<string | null> {
return rpc<string | null>("cmd_http_response_body_path", { responseId: id });
}
/**
* Base64 for the trip over IPC, in chunks so a few megabytes don't blow the
* argument limit. The engine's write command speaks base64; only this host has
* to care.
*/
function toBase64(bytes: Uint8Array): string {
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
export function createTauriPlatform(): Platform {
const window = createWindow();
return {
capabilities: ALL_CAPABILITIES,
httpProxyUrl: null,
window,
clipboard: {
@@ -135,7 +150,7 @@ export function createTauriPlatform(): Platform {
dialog: {
// Overloaded on the interface; one implementation covers both shapes.
open: ((options?: OpenDialogOptions) => open(options)) as Platform["dialog"]["open"],
save: (options) => save(options ?? {}),
save: (options) => saveDialog(options ?? {}),
},
files: {
@@ -144,6 +159,18 @@ export function createTauriPlatform(): Platform {
url: (path) => convertFileSrc(path),
basename: (path) => basename(path),
resolveResource: (path) => resolveResource(path),
async save(suggestedName, content, filters) {
const path = await saveDialog({ defaultPath: suggestedName, filters });
if (path == null) return null;
// Not the fs plugin: its ACL is read-only and scoped to the app's own
// directories, and a path the user just picked is neither. The engine
// writes it, which is where the desktop has always written it — and it
// speaks base64, so content that is already base64 goes straight over.
const data = content instanceof Uint8Array ? toBase64(content) : content.base64;
await rpc("cmd_save_base64_to_binary", { filepath: path, data });
return path;
},
},
blobs: {
+34
View File
@@ -40,6 +40,17 @@ export interface RpcStreamHandle<T> {
unlisten: Unsubscribe;
}
/**
* What to save: the bytes, or base64 of them for a caller that already has it
* that way.
*
* Both forms exist because both hosts want a different one, and a value that
* arrives base64 should not be decoded and re-encoded to get back where it
* started. Whichever a caller has is the one to pass; each host converts only
* when it has to.
*/
export type SaveContent = Uint8Array | { base64: string };
export interface DialogFilter {
name: string;
extensions: string[];
@@ -157,6 +168,25 @@ export interface PlatformFiles {
/** Resolve a path bundled with the app itself, rather than one from the backend. */
resolveResource(path: string): Promise<string>;
/**
* Put bytes somewhere the user chooses. Returns where they went — a path, a
* filename, whatever this host can say — or null if the user backed out.
*
* The caller supplies the bytes, which is the whole point: the alternative
* shape, where a dialog mints a path and a separate backend command writes to
* it, can only work on a host that has both a filesystem and a backend. A tab
* has neither, so every one of those call sites was a dead control. Whoever
* produces the bytes already knows what they are; the host only has to know
* where they go.
*
* `suggestedName` is what the save dialog opens with, extension included.
*/
save(
suggestedName: string,
content: SaveContent,
filters?: DialogFilter[],
): Promise<string | null>;
}
/**
@@ -186,6 +216,8 @@ export interface PlatformBlobs {
export interface Platform {
readonly capabilities: PlatformCapabilities;
/** Web request relay, or null when this host executes requests itself. */
readonly httpProxyUrl: string | null;
readonly window: PlatformWindow;
readonly clipboard: PlatformClipboard;
readonly dialog: PlatformDialog;
@@ -281,6 +313,8 @@ export interface PlatformCapabilities {
systemFonts: boolean;
/** Commercial licence activation. */
license: boolean;
/** Connecting local AI agents through the Yaak CLI on this machine. */
agents: boolean;
}
export type CapabilityName = keyof PlatformCapabilities;
+44 -43
View File
@@ -5,10 +5,11 @@ model layer — `yaak-models`, SQLite included — runs compiled to wasm inside
worker the tab talks to, so a browser stores exactly what a desktop install
stores, migrations and all.
Select it at build time and run the frontend alone:
Select it at build time. `vp run web:dev` does that and starts the send server
alongside the frontend:
```shell
YAAK_TARGET=web npm run dev --workspace @yaakapp/yaak-client
vp run web:dev
```
The flag resolves `@yaakapp-internal/platform` to `../index.web.ts`, which
@@ -30,17 +31,17 @@ tab (index.ts, commands.ts) ──MessagePort──▶ worker.ts ──▶ @yaak
◀── NDJSON: events, response, body, cookies ──
```
| File | What it is |
| --- | --- |
| `index.ts` | The `Platform` implementation. |
| `commands.ts` | The command table: model commands forward to the worker; the rest is fixed answers and refusals-with-a-reason. |
| `connection.ts` | A tab's end of the wire: request/response over a `MessagePort`, event delivery, and the tab's identity (`label`). |
| `send.ts` | Sending: the worker renders (`prepare_http_send`), the server executes, this file stores what comes back where the desktop stores it. |
| `server.ts` | Where the Yaak server is, and the wire shapes it speaks (generated from `crates-server/yaak-web/src/wire.rs`). |
| `worker.ts` | The process that owns the database. Loads the wasm, opens the DB once, answers each port, fans `model_writes` out to every port. |
| `protocol.ts` | The message shapes both sides import. |
| `errors.ts` | `UnsupportedCommandError`, the structured refusal. |
| `storage.ts` | `navigator.storage.persist()`. |
| File | What it is |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `index.ts` | The `Platform` implementation. |
| `commands.ts` | The command table: model commands forward to the worker; the rest is fixed answers and refusals-with-a-reason. |
| `connection.ts` | A tab's end of the wire: request/response over a `MessagePort`, event delivery, and the tab's identity (`label`). |
| `send.ts` | Sending: the worker renders (`prepare_http_send`), the server executes, this file stores what comes back where the desktop stores it. |
| `server.ts` | Where the Yaak server is, and the wire shapes it speaks (generated from `crates-server/yaak-web/src/wire.rs`). |
| `worker.ts` | The process that owns the database. Loads the wasm, opens the DB once, answers each port, fans `model_writes` out to every port. |
| `protocol.ts` | The message shapes both sides import. |
| `errors.ts` | `UnsupportedCommandError`, the structured refusal. |
| `storage.ts` | `navigator.storage.persist()`. |
The Rust side is `crates/yaak-wasm` (`@yaakapp-internal/wasm`): `boot()`,
`rpc(cmd, payload, label)` returning `{ result, events }`, blob get/put, and
@@ -70,7 +71,7 @@ Behaviours worth knowing before changing anything:
store's echo handling is unchanged.
- **Cascade rules, duplicate naming, id generation, serde defaults, and the
lazy first-run bootstrap are all the Rust code's.** Nothing about what a
model *is* is decided in TypeScript.
model _is_ is decided in TypeScript.
- **Persistence is `relaxed-idb`**: SQLite pages live in IndexedDB, writes land
in memory and flush shortly after. A tab closing mid-flush loses at most the
last few writes.
@@ -82,14 +83,14 @@ Behaviours worth knowing before changing anything:
### Implemented (32)
| Group | Commands |
| --- | --- |
| Models | `models_workspace_models`, `models_upsert`, `models_delete`, `models_duplicate`, `models_get_settings`, `models_get_graphql_introspection`, `models_upsert_graphql_introspection`, `models_grpc_events`, `models_websocket_events` |
| Sending | `cmd_send_http_request` (through the Yaak server; see below) |
| App | `cmd_metadata`, `cmd_get_workspace_meta`, `cmd_default_headers`, `cmd_get_themes`, `cmd_check_for_updates`, `cmd_dismiss_notification`, `cmd_plugin_init_errors` |
| Bodies | `cmd_http_response_body`, `cmd_http_response_body_path`, `cmd_http_request_body`, `cmd_get_http_response_events`, `cmd_get_sse_events` |
| Group | Commands |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Models | `models_workspace_models`, `models_upsert`, `models_delete`, `models_duplicate`, `models_get_settings`, `models_get_graphql_introspection`, `models_upsert_graphql_introspection`, `models_grpc_events`, `models_websocket_events` |
| Sending | `cmd_send_http_request` (through the Yaak server; see below) |
| App | `cmd_metadata`, `cmd_get_workspace_meta`, `cmd_default_headers`, `cmd_get_themes`, `cmd_check_for_updates`, `cmd_dismiss_notification`, `cmd_plugin_init_errors` |
| Bodies | `cmd_http_response_body`, `cmd_http_response_body_path`, `cmd_http_request_body`, `cmd_get_http_response_events`, `cmd_get_sse_events` |
| Plugin surfaces (empty results) | `cmd_http_request_actions`, `cmd_websocket_request_actions`, `cmd_grpc_request_actions`, `cmd_workspace_actions`, `cmd_folder_actions`, `cmd_template_function_summaries`, `cmd_get_http_authentication_summaries`, `cmd_get_http_authentication_config` |
| Text | `cmd_format_json`, `cmd_render_template` |
| Text | `cmd_format_json`, `cmd_render_template` |
Some of these answer honestly rather than fully, and the difference matters:
@@ -112,15 +113,15 @@ Each returns an `UnsupportedCommandError` carrying `cmd`, a user-facing
`message`, and the `capability` a caller should have checked. The UI turns it
into a toast.
| Reason | Commands |
| --- | --- |
| Sending, the parts not wired yet | `cmd_send_ephemeral_request`, `cmd_delete_send_history`, `cmd_delete_all_http_responses`, `cmd_import_url` |
| No plugin runtime | `cmd_reload_plugins`, `cmd_plugin_info`, `cmd_plugins_search`, `cmd_plugins_install`, `cmd_plugins_install_from_directory`, `cmd_plugins_uninstall`, `cmd_plugins_updates`, `cmd_plugins_update_all`, `cmd_template_function_config`, `cmd_template_tokens_to_string`, `cmd_call_http_request_action`, `cmd_call_websocket_request_action`, `cmd_call_grpc_request_action`, `cmd_call_workspace_action`, `cmd_call_folder_action`, `cmd_call_http_authentication_action`, `cmd_curl_to_request`, `cmd_format_graphql` |
| No filesystem | `cmd_import_data`, `cmd_export_data`, `cmd_save_response`, `cmd_save_base64_to_binary` |
| Needs a real socket | `cmd_grpc_reflect`, `cmd_grpc_go`, `cmd_delete_all_grpc_connections`, `cmd_ws_connect`, `cmd_ws_send`, `cmd_ws_close`, `cmd_ws_delete_connections` |
| Workspace encryption | `cmd_enable_encryption`, `cmd_disable_encryption`, `cmd_reveal_workspace_key`, `cmd_set_workspace_key`, `cmd_secure_template`, `cmd_decrypt_template` |
| One tab, no windows | `cmd_new_child_window`, `cmd_new_main_window`, `cmd_restart` |
| Other | `cmd_send_feedback` |
| Reason | Commands |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Sending, the parts not wired yet | `cmd_send_ephemeral_request`, `cmd_delete_send_history`, `cmd_delete_all_http_responses`, `cmd_import_url` |
| No plugin runtime | `cmd_reload_plugins`, `cmd_plugin_info`, `cmd_plugins_search`, `cmd_plugins_install`, `cmd_plugins_install_from_directory`, `cmd_plugins_uninstall`, `cmd_plugins_updates`, `cmd_plugins_update_all`, `cmd_template_function_config`, `cmd_template_tokens_to_string`, `cmd_call_http_request_action`, `cmd_call_websocket_request_action`, `cmd_call_grpc_request_action`, `cmd_call_workspace_action`, `cmd_call_folder_action`, `cmd_call_http_authentication_action`, `cmd_curl_to_request`, `cmd_format_graphql` |
| No filesystem | `cmd_import_data`, `cmd_export_data`, `cmd_save_response`, `cmd_save_base64_to_binary` |
| Needs a real socket | `cmd_grpc_reflect`, `cmd_grpc_go`, `cmd_delete_all_grpc_connections`, `cmd_ws_connect`, `cmd_ws_send`, `cmd_ws_close`, `cmd_ws_delete_connections` |
| Workspace encryption | `cmd_enable_encryption`, `cmd_disable_encryption`, `cmd_reveal_workspace_key`, `cmd_set_workspace_key`, `cmd_secure_template`, `cmd_decrypt_template` |
| One tab, no windows | `cmd_new_child_window`, `cmd_new_main_window`, `cmd_restart` |
| Other | `cmd_send_feedback` |
### Refused generically (34)
@@ -136,14 +137,14 @@ should be able to see which.
Reported honestly, so callers gate on the question rather than on the host:
| True | False |
| --- | --- |
| True | False |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `httpSending`, `timeline`, `cookieJar` | `grpc`, `websocket`, `git`, `sync`, `tlsOptions`, `localFiles`, `multiWindow`, `windowChrome`, `interfaceZoom`, `plugins`, `encryption`, `updater`, `clipboardRead`, `systemFonts`, `license` |
`interfaceZoom: false` leaves Cmd/Ctrl `+`, `-` and `0` to the browser instead
of swallowing them, and drops those three rows from the hotkeys screen.
`multiWindow: false` means the host cannot open a *second window* on demand —
`multiWindow: false` means the host cannot open a _second window_ on demand —
what `cmd_new_child_window` does for Settings and workspace switching. It is not
a claim that nothing else is looking: other tabs may well be open on the same
worker, and it pushes every write to all of them regardless.
@@ -159,7 +160,7 @@ for the desktop's window label. The worker fans each write out to every
connected tab, and the receiving tab's store applies or ignores it exactly as a
desktop window would.
The label is deliberately *not* kept in `sessionStorage`: duplicating a tab
The label is deliberately _not_ kept in `sessionStorage`: duplicating a tab
copies session storage, and two tabs sharing one identity would each mistake the
other's writes for an echo of their own and drop them.
@@ -207,7 +208,7 @@ network half of a send runs on a small stateless server,
**What sends today:** any saved request whose templates are variables and whose
authentication is none, or an inline header. Sending a request that needs a
template *function* (`${[ timestamp() ]}`) or an authentication plugin (bearer,
template _function_ (`${[ timestamp() ]}`) or an authentication plugin (bearer,
basic, OAuth, …) is refused before anything leaves the tab, with a message naming
what it needs; those light up when plugins run in the browser. Requests with a
file body or multipart file fields are refused by the server (it has no access to
@@ -217,11 +218,11 @@ private ranges outright — that is what the desktop app is for. A self-hosted
server on your own network can be started with `--allow-private-networks`, which
is the one case where those addresses are the user's to reach.
**Where the tab sends** (`server.ts`): a production build posts to `/v1/http/send`
on its own origin, because the server can serve the app itself
(`yaak-web --serve dist/apps/yaak-client`, which is what the
`ghcr.io/mountain-loop/yaak-web` image runs) — same origin, so no CORS and
nothing to configure. A dev build falls back to `http://127.0.0.1:9227`, since
the Vite server is a different origin and serves no `/v1`; run one with
`cargo run -p yaak-web`. `VITE_YAAK_WEB_URL` overrides both, for a
deployment that keeps the app and the server apart.
**Where the tab sends** (`server.ts`): its own origin, in development as well as
production, so there is no address to learn and no CORS in the loop. A
production build is served by the sender itself (`yaak-web --serve
dist/apps/yaak-client`, which is what the `ghcr.io/mountain-loop/yaak-web`
image runs). In development the Vite server passes `/v1` through to `yaak-web`
instead, following `PORT` to find it — `vp run web:dev` starts both.
`VITE_YAAK_WEB_URL` overrides this, for a deployment that keeps the app and the
server apart.
+13 -3
View File
@@ -203,7 +203,7 @@ const HANDLERS: Partial<Record<AppCmd, Handler>> = {
if (str(payload, "filter") != null) {
return {
content: "",
error: "Response filters come from a plugin, which this host doesn't run yet",
error: "Response filters are not available in the browser yet",
};
}
@@ -228,6 +228,16 @@ const HANDLERS: Partial<Record<AppCmd, Handler>> = {
// The rows the sender wrote for that response, same table as the desktop.
cmd_get_http_response_events: (payload, db) => db.rpc("cmd_get_http_response_events", payload),
/* ------------------------------- export -------------------------------- */
// Built by the model layer, exactly as the desktop and the CLI build it. Where
// the document goes is not decided here: the caller hands it to `files.save`,
// which is the one thing each host answers differently.
cmd_export_data: (payload, db) => db.rpc("cmd_export_data", payload),
// The same example the desktop creates, built by the model layer in the worker.
cmd_create_example_workspace: (payload, db) => db.rpc("cmd_create_example_workspace", payload),
async cmd_get_sse_events() {
return [];
},
@@ -243,6 +253,7 @@ const HTTP_AUTHENTICATION_SUMMARIES = [
{ name: "aws", label: "AWS SigV4", shortLabel: "AWS" },
{ name: "basic", label: "Basic Auth", shortLabel: "Basic" },
{ name: "bearer", label: "Bearer Token", shortLabel: "Bearer" },
{ name: "digest", label: "Digest Auth", shortLabel: "Digest" },
{ name: "jwt", label: "JWT Bearer", shortLabel: "JWT" },
{ name: "ntlm", label: "NTLM", shortLabel: "NTLM" },
{ name: "oauth1", label: "OAuth 1.0", shortLabel: "OAuth 1" },
@@ -281,11 +292,10 @@ const DECLINED: Partial<Record<AppCmd, [reason: string, capability: CapabilityNa
"Importing from a file needs a filesystem, which a browser tab has no",
"localFiles",
],
cmd_import_url: ["Importing from a URL needs the Yaak server, which isn't available yet", null],
cmd_commit_import: ["Importing needs a plugin, which this host doesn't run", null],
cmd_list_import_sources: ["Importing isn't available in the browser yet", null],
cmd_import_sources_for_origin: ["Importing isn't available in the browser yet", null],
cmd_export_data: ["Exporting to a file isn't available in the browser yet", "localFiles"],
cmd_detect_import_source: ["Importing isn't available in the browser yet", null],
cmd_save_response: ["Saving a response to disk isn't available in the browser", "localFiles"],
cmd_save_base64_to_binary: ["Saving to disk isn't available in the browser", "localFiles"],
cmd_format_graphql: ["Formatting GraphQL needs a plugin, which this host doesn't run", null],
+2 -1
View File
@@ -11,6 +11,7 @@
*/
import type { Unsubscribe } from "../types";
import { randomId } from "./ids";
import { type FromWorker, type ToWorker, WORKER_NAME } from "./protocol";
/**
@@ -45,7 +46,7 @@ export class WorkerConnection {
* and two tabs claiming one identity would each drop the other's writes as
* echoes.
*/
readonly label = `tab_${crypto.randomUUID().slice(0, 8)}`;
readonly label = `tab_${randomId(4)}`;
/** True once the worker has said anything at all. */
private heard = false;
+14
View File
@@ -0,0 +1,14 @@
/**
* Random ids that do not need a secure context.
*
* `crypto.randomUUID` exists only on HTTPS and localhost, so a tab opened at
* `http://some-host:1424` — a self-hosted instance reached from another machine —
* throws on it before anything renders. `crypto.getRandomValues` carries no such
* restriction, and nothing here needs UUID semantics: these ids identify a tab and
* a stream within one page, and only have to not collide with each other.
*/
export function randomId(bytes = 8): string {
const buf = new Uint8Array(bytes);
crypto.getRandomValues(buf);
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
}
+115 -5
View File
@@ -16,6 +16,7 @@
*/
import type {
DialogFilter,
DragDropEvent,
OsType,
Platform,
@@ -23,11 +24,14 @@ import type {
PlatformWindow,
RpcPayload,
RpcStreamHandle,
SaveContent,
Unsubscribe,
} from "../types";
import { commandSupport, runCommand } from "./commands";
import { WorkerConnection } from "./connection";
import { unsupported } from "./errors";
import { randomId } from "./ids";
import { serverBaseUrl } from "./server";
import { requestPersistence } from "./storage";
/** What this host can do, reported honestly. */
@@ -68,6 +72,8 @@ function capabilitiesFor(): PlatformCapabilities {
clipboardRead: false,
systemFonts: false,
license: false,
// No local CLI to find and no app process to serve MCP from.
agents: false,
};
}
@@ -106,6 +112,91 @@ async function hostPluginCommand<T>(cmd: string, payload?: RpcPayload): Promise<
}
}
/**
* The File System Access API, where the browser has it. Chromium does; Firefox
* and Safari do not, and fall through to a download below.
*/
interface SaveFilePicker {
(options: {
suggestedName?: string;
types?: { description: string; accept: Record<string, string[]> }[];
}): Promise<{
name: string;
createWritable(): Promise<{ write(data: Uint8Array): Promise<void>; close(): Promise<void> }>;
}>;
}
/**
* Saving, the only way a page can: a real save dialog where the browser offers
* one, and a download everywhere else.
*
* The return value is a name rather than a path because a name is all a tab
* ever learns. Callers show it back to the user and nothing more, which is why
* the interface promises "where they went" rather than a path.
*/
function toBytes(content: SaveContent): Uint8Array {
if (content instanceof Uint8Array) return content;
const binary = atob(content.base64);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
async function saveBytes(
suggestedName: string,
content: SaveContent,
filters?: DialogFilter[],
): Promise<string | null> {
const picker = (window as unknown as { showSaveFilePicker?: SaveFilePicker }).showSaveFilePicker;
const bytes = toBytes(content);
if (picker != null) {
let handle;
try {
handle = await picker({
suggestedName,
types: filters?.map((f) => ({
description: f.name,
// The API keys accepted extensions by MIME type. Nothing here knows
// the real one, and it only labels the dialog's filter, so the
// catch-all is honest enough.
accept: { "application/octet-stream": f.extensions.map((e) => `.${e}`) },
})),
});
} catch (err) {
// Only choosing a file is allowed to fall back. Backing out is not a
// failure and must not become a download nobody asked for; anything else
// here is a browser that won't show the dialog, which a download covers.
if ((err as { name?: string } | null)?.name === "AbortError") return null;
console.warn("Save dialog unavailable, falling back to a download", err);
}
// Past the dialog, the user has named a destination. A write that fails
// there is a failed save, and saying so beats quietly putting the file
// somewhere else and reporting success.
if (handle != null) {
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
return handle.name;
}
}
// No dialog: the file lands wherever the browser puts downloads, under the
// name we suggested. The user is not asked, so there is nothing to cancel.
const url = URL.createObjectURL(new Blob([bytes as BlobPart]));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = suggestedName;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
// Revoked on a later turn: revoking while the browser is still reading the
// blob cancels the download in some of them.
setTimeout(() => URL.revokeObjectURL(url), 30_000);
return suggestedName;
}
function createWindow(db: WorkerConnection): PlatformWindow {
const noop = async () => {};
@@ -177,15 +268,24 @@ export function createWebPlatform(): Platform {
return {
capabilities,
httpProxyUrl: serverBaseUrl() || window.location.origin,
window: createWindow(db),
clipboard: {
writeText: (text) => navigator.clipboard.writeText(text),
readText: async () => {
throw unsupported("clipboard.readText", "Paste instead — Yaak in a browser can't read the clipboard on its own", "clipboardRead");
throw unsupported(
"clipboard.readText",
"Paste instead — Yaak in a browser can't read the clipboard on its own",
"clipboardRead",
);
},
clear: async () => {
throw unsupported("clipboard.clear", "Yaak in a browser can't modify the clipboard", "clipboardRead");
throw unsupported(
"clipboard.clear",
"Yaak in a browser can't modify the clipboard",
"clipboardRead",
);
},
},
@@ -198,7 +298,11 @@ export function createWebPlatform(): Platform {
files: {
readDir: async () => {
throw unsupported("files.readDir", "A browser tab can't browse your filesystem", "localFiles");
throw unsupported(
"files.readDir",
"A browser tab can't browse your filesystem",
"localFiles",
);
},
readText: async () => {
throw unsupported("files.readText", "A browser tab can't read local files", "localFiles");
@@ -207,6 +311,8 @@ export function createWebPlatform(): Platform {
url: (path) => path,
basename: async (path) => path.split(/[/\\]/).pop() ?? path,
resolveResource: async (path) => path,
save: saveBytes,
},
/**
@@ -241,7 +347,7 @@ export function createWebPlatform(): Platform {
): Promise<RpcStreamHandle<T>> {
// Same shape as the desktop — subscribe first, then dispatch — so that a
// command which grows the ability to stream here needs no caller changes.
const streamId = crypto.randomUUID();
const streamId = randomId();
const unlisten = db.listen(`stream_${streamId}`, (p) => onMessage(p as M));
try {
const result = (await runCommand(cmd, { ...payload, streamId }, db)) as T;
@@ -266,7 +372,11 @@ export function createWebPlatform(): Platform {
},
revealItemInDir: async () => {
throw unsupported("revealItemInDir", "A browser tab can't open your file manager", "localFiles");
throw unsupported(
"revealItemInDir",
"A browser tab can't open your file manager",
"localFiles",
);
},
osType: detectOsType,
+6 -6
View File
@@ -16,16 +16,16 @@ import type { Frame } from "@yaakapp-internal/web";
* (`yaak-web --serve`), and then a send is a request to a path on the
* page's own origin — no CORS, and nothing for a self-hoster to configure.
*
* `VITE_YAAK_WEB_URL` overrides it at build time, for a deployment that
* keeps the two apart. The dev server is one of those: it serves the app on its
* own origin and knows nothing about `/v1`, so a dev build falls back to a server
* running locally (`cargo run -p yaak-web`).
* `VITE_YAAK_WEB_URL` overrides it at build time, for a deployment that keeps the
* two apart. Nothing else needs to: the dev server passes `/v1` through to
* `yaak-web` (see the client's vite config), so a dev build and a production
* build are both talking to their own origin, and neither has an address to
* learn. A tab opened from another machine therefore works unchanged.
*/
export function serverBaseUrl(): string {
const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env;
const configured = env?.VITE_YAAK_WEB_URL?.trim();
if (configured) return configured.replace(/\/+$/, "");
return env?.DEV ? "http://127.0.0.1:9227" : "";
return configured ? configured.replace(/\/+$/, "") : "";
}
export function serverSendUrl(): string {