Webviews and storage
Use the typed webview client for commands, files, navigation, preferences, and host context.
Webview Client
Webviews talk to the host through a typed client instead of raw host.call strings.
createWebviewClient builds one from the extension’s exported commands record and
settings contribution. Import both as types only, so no server code enters the webview
bundle.
import { createWebviewClient, defineExtensionView } from "@pstdio/sdk/extensions";
import type { commands } from "../commands";
import type { settings } from "../settings";
export default defineExtensionView({
render({ mount, host }) {
const client = createWebviewClient<typeof commands, typeof settings>(host);
// ...
},
});
client.commandshas one function per command key. Params come from the command’sparamsschema and the result from itsrunreturn type. Bare keys resolve inside the declaring extension; the host bridge provides the extension id. Failed outcomes throw with the outcome reason.client.settingshas typedall,get,set, anddeletefrom the settings contribution. Declare the settings contributionas constand export it so the types stay precise.await client.settings.delete(key)removes the stored override and restores its declared fallback.setreturns the saved value, including changes made by the host. Deletion does not storenull; declare theextension.settings.deletecapability.client.artifactshaslist(mount, prefix?),readText(mount, path), andimageUrl(mount, path)for artifact mounts the webview declared withartifactsRead(mount)(see Artifact mounts and storage).imageUrlreturns a short-lived URL for png, jpeg, webp, or gif, usable in<img src>; request a fresh URL when one expires. Undeclared mounts are denied by the capability gate with the exact missing declaration, such asartifacts.read:runs.client.filespicks local files and stores extension-owned files. See Webview files.client.navigation.openopens an explicit page or panel target. See Navigate from a webview.- Author commands with
defineCommand. Commands written as inline literals insidedefineExtensionkeep untyped results (see ADR 0012). - Pass
{ extensionId }as the second argument only in tests, where no host bridge provides one.
View render context
render receives one context object. These parts are in 0.43.x and main, except page:
| Member | What it does |
|---|---|
mount |
The DOM element the view renders into. |
host.call(method, params?) |
Calls a host capability that the webview declared. |
host.onEvent(scope, handler) |
Listens to host messages on one scope and returns an unsubscribe function. The webview events client uses the extension.events scope; prefer it for extension events. |
files |
Picks local files and stores extension-owned files. See Webview files. |
propsStore.get() |
Returns the current props the host passed to the view. |
propsStore.subscribe(listener) |
Calls listener with new props whenever the host changes them. Returns an unsubscribe function. |
page |
Reads and updates page params. On main only; it ships in the release after 0.43.x. See Page params. |
locale, t |
The active locale and a translation helper. |
Webview files
Use client.files. The old render-context files helper is deprecated through 0.44.
pick opens the browser’s
file picker and does not contact the host. Upload, list, and delete cross the webview
bridge, so the view must declare each method it calls.
const imports = defineView({
id: "imports",
title: "Imports",
body: {
kind: "webview",
entry: packageAsset("./webviews/imports.ts", import.meta.url),
capabilities: ["files.upload"],
},
});
| Method | Declaration | Input | Result |
|---|---|---|---|
files.pick(options?) |
None | { accept?, multiple? } |
Browser File[]; an empty array means the user cancelled. |
files.upload(input) |
files.upload |
{ name, data, mimeType?, scope? } |
The stored ExtensionBlobRef. data accepts Uint8Array or ArrayBuffer. |
files.download(input) |
files.download |
{ name, data, mimeType? } |
Starts a download on the user’s device. data accepts Uint8Array or ArrayBuffer; name is a filename, without a directory. |
files.list(input?) |
files.list |
{ scope? } |
ExtensionBlobRef[] for the exact scope. |
files.delete(id) |
files.delete |
A file id returned by upload or list. | Resolves after the host deletes the owned file. |
On main, the API 0.5.0 host and SDK add client.files.download. Read or generate
the bytes through the extension’s existing commands, then pass them to this
method. The host initiates the download outside the sandbox; extension and
artifact frames retain their existing sandbox permissions. No URL or filesystem
path is accepted, and this capability grants no additional file read access.
The promise resolves after initiation. The browser’s download UI owns completion,
cancellation and the final location; it does not report a successful disk save to
the extension. A rejected bridge call can be shown beside the export control and
retried. Publish the supporting SDK and host before releasing a consumer.
import { createWebviewClient, defineExtensionView } from "@pstdio/sdk/extensions";
export default defineExtensionView({
async render({ host, mount }) {
const files = createWebviewClient(host).files;
const [selected] = await files.pick({ accept: ".csv,text/csv" });
if (!selected) return;
const uploaded = await files.upload({
name: selected.name,
data: await selected.arrayBuffer(),
mimeType: selected.type || "text/csv",
});
mount.textContent = `Uploaded ${uploaded.name}.`;
},
});
files.list and files.delete remain callable but are deprecated in 0.44. Use extension
commands and owned storage for durable file workflows.
The host, not the guest, selects the active project and extension instance. A webview cannot use a request field to read or write another extension’s files. The optional scope only groups files inside that owner boundary:
| Scope | Webview value | Meaning |
|---|---|---|
| Project | Omit scope or use { type: "project" } |
Files shared by this extension across the active project. |
| Resource | { type: "resource", id: resourceId } |
Files grouped under one resource id. |
| Extension-defined | { type: "import", id: importId } |
Files grouped by a type and id chosen by the extension. Include the id when a command must access the scope. |
Upload and list must use the same scope to find the same files. The default project
scope matches ctx.storage.files in commands. A command can read the bytes without a
second upload:
const contents = await ctx.storage.files.getBytes(params.fileId);
The command storage API names the same scopes with runtime objects, not the webview
{ type, id } shape:
| Webview scope | Matching command storage |
|---|---|
Omitted or { type: "project" } |
ctx.storage.files |
{ type: "resource", id: resource.id } |
ctx.storage.scope({ type: "resource", resource }).files, where resource is the full { type, id, ... } resource reference. |
{ type: "import", id: importId } |
ctx.storage.scope({ type: "import", id: importId }).files |
Resource scopes use a full resource reference. Extension-defined command scopes
require an id. The upload limit is 25 MiB. The
returned ExtensionBlobRef contains id, name, mimeType, size, hash, url,
createdAt, and updatedAt.
Host-backed file methods need a project extension instance. They are available to
declared project pages, panels, and project settings views. A global
settings view has no project file owner, so it does not receive these methods. Keep
files.pick available there only when selecting a local file without uploading it.
The declaration gate still applies. If the view omits a declaration, the bridge rejects the call before it reaches the file host.
Embedded harness controls and resource actions
On main, extension API 0.2.1 adds two declared webview capabilities. Use harnesses.read to read the current project’s harnesses, available models, model-specific parameter schema, defaults, and initial selection. Without input, the selection matches the native harness field: the project’s last-used harness, then the project default, then the first available harness. Pass an optional harnessId and model to read another choice. If the model is not offered, the host picks one that is, and the schema and defaults always belong to the returned selection.model. The host owns the project scope. The extension testbench answers with a scripted harness. Render the returned data with HarnessModelPicker and HarnessParamEditor from @pstdio/ui/param-editor to keep the model and its run options in your own form.
Use resources.actions with { operation: "list", resource } to read the same current menu actions as a native resource card. Pass the resource’s own extensionId for extension resource kinds; the host does not fill it in with the calling extension. Each action has a label, a workbench icon name or an iconSrc image URL, isDisabled, and a description that explains a disabled action. Render those actions with ResourceContextMenu. Invoke one with { operation: "execute", resource, key }. The host resolves the menu again before execution, applies its availability rules, and opens the normal parameter form when an action needs input. The call rejects when the action is no longer available or its command fails, so the webview reports the error. A listed snapshot does not update by itself. After the first list, the host sends { type: "changed" } on the resources.actions event scope whenever the actions may have changed. Listen with host.onEvent("resources.actions", ...) and list again. Declare each named capability on the view.
Live reader actions in native resource menus
On main, API 0.5.0 adds registerWebviewResourceAction(host, action, run).
Declare resources.actions.register on the view. Pass its current resource,
label and optional icon. The host adds the action to that reader’s breadcrumb
and tab resource menus, beside persistent resource commands such as Rename and
Delete. It is scoped to the exact project, placement, extension and resource;
it is omitted from other readers and unopened-resource menus.
The returned ready promise reports registration errors. Await dispose() when
the view unmounts or changes resource. The callback receives an AbortSignal;
check it after awaited work and before downloading or another external effect.
The native action awaits completion and reports callback failures normally.
Disconnect removes the action and rejects pending invocations. Invocations are
never queued for a later frame. Declare files.download separately to export.
import { createWebviewClient, registerWebviewResourceAction } from "@pstdio/sdk/extensions";
const action = registerWebviewResourceAction(host, {
resource,
label: "Export report",
icon: "download",
}, async (signal) => {
const data = new TextEncoder().encode("Report contents");
signal.throwIfAborted();
await createWebviewClient(host).files.download({ name: "report.txt", data, mimeType: "text/plain" });
});
await action.ready;
// Dispose when this reader's owner changes or unmounts.
await action.dispose();
A reader can supply choices: [{ id, label, selected?, disabled? }] on the same
registration to contribute a mutually exclusive group to that resource dropdown.
The callback receives (signal, choiceId). A group counts as one of the view’s
32 leases and accepts up to 1024 choices with unique IDs and at most one selected
value. The host validates the selected ID and renders checked radio menu items.
Use await action.updateChoices(nextChoices, { label? }) when the available or selected
values change. This updates the menu without cancelling an accepted callback;
replacing or disconnecting the owning view still cancels it normally.
Choice IDs retain their native menu identity across updates. An optional
kind: "action" row renders as an ordinary action in the same group and cannot
be selected. Set closeOnSelect: false for paging controls that keep the menu
open. Page large collections before registering them and keep labels within
1000 characters.
Cloud account and sync status
On main, extension API 0.2.1 also adds account.read and account.manage. client.account has the same methods as ctx.account. Declare account.read for client.account.status, loginStatus, devices, and projectSyncStatus. Declare account.manage for client.account.login, cancelLogin, logout, renameDevice, removeDevice, syncProject, stopProjectSync, and resolveReturnedChanges. Without a project ID, a call uses the webview’s project.
const client = createWebviewClient<typeof commands>(host);
const refresh = async () => render(await client.account.projectSyncStatus());
await refresh();
const stop = client.events.subscribe(accountEvents.projectSyncChanged, refresh);
On main, API 0.4.2 adds client.account.query(source), a readonly retained query for {service:"status"}, {service:"projectSyncStatus", projectId} or {service:"devices", accountId, managerOrigin}. Declare account.read and observe it with useWebviewCommandQuery(query, useWebviewVisibility()). The runtime identity guard owns status; project and device reads are fenced by account and server identity. Optional view cancellation preserves another reader and the mandatory guard. Publish the matching host and SDK before independent adoption.
The dashboard delivers accountEvents.projectSyncChanged only to webviews of the project that changed. The extension testbench does not provide an account; both capabilities answer unsupported there.
Navigate from a webview
Add navigation.open to the view and pass an explicit page or panel target:
const details = defineView({
id: "details",
title: "Details",
body: {
kind: "webview",
entry: packageAsset("./webviews/details.ts", import.meta.url),
capabilities: ["navigation.open"],
},
});
await client.navigation.open({
kind: "page",
page: { kind: "page", id: "ticket" },
resource: {
type: "ticket",
id: "PS-260",
label: "Dashboard webview capabilities",
metadata: { status: "in-review" },
},
});
The target chooses the destination. A resource supplies identity and input only. The
dashboard does not search for a matching screen by resource kind. The bridge rejects
the call if the view did not declare navigation.open or the target is invalid.
@pstdio/sdk/extensions/react ships react-query hooks built on the client. react and
@tanstack/react-query are optional peer dependencies used only by this entry.
On main for API 0.4.0, client.queries, useWebviewQuery and useScopedQuery
provide common project/authority identity, retained finite reads and scoped
invalidation without a per-component refresh controller. Declare both React peers
when importing this entry. Use the
state and project lifetime guide
for new consumers, command-backed editing, committed storage observation and the
reusable lifecycle fixture. Existing useCommandQuery consumers retain the
QueryClientProvider contract below.
The webview query client also provides these lifetime methods:
| Method | Purpose |
|---|---|
client.queries.getScope() |
Read a stable serialized key for the selected runtime, account/origin and project, suitable for external-store snapshot comparison. |
client.queries.subscribeScope(listener) |
Observe host scope updates; the returned function detaches the listener. Compare getScope() to ignore unrelated host props. |
client.queries.inspect() |
Read active query and total retained-owner counts for lifecycle diagnostics. |
client.queries.dispose() |
Retire this guest host’s shared query root and release its subscriptions. Reserve this for the owning host’s teardown, since peer views share that root. |
ctx.storage.observe(changed, { recordIds?, signal? }) observes committed structured
records in the calling project and extension, including local signed-out commits.
Record IDs are opaque records.id() identities. Install observation before its
finite read; close the returned handle or abort its signal to detach.
await ctx.sessions.observeMetadata(sessionId, changed, { signal? }) installs
shared host observation for the session’s session, workspace, harness and
execution field-group hints. It does not carry transcript or queue snapshots.
Await installation before the baseline reads and close the returned handle or
abort the signal when optional observation ends.
import { useCommandMutation, useCommandQuery } from "@pstdio/sdk/extensions/react";
const statuses = useCommandQuery({
queryKey: ["ticket-statuses"],
command: client.commands["ticket-status.read"],
refreshOn: { client, events: ["pstdio.planner.statuses-changed"] },
});
const saveStatus = useCommandMutation({
command: client.commands["ticket-status.update"],
invalidate: [["ticket-statuses"]],
});
refreshOn subscribes to each event, refetches matching queries and refreshes after a host
reconnect. Events during a pending read queue one later read; simultaneous reset callbacks
share that refresh. Subscriptions stop on
unmount. Set enabled: false to disable both the query and its refresh subscriptions.
Host context and capability errors
defineExtensionView types its render props as WebviewHostProps by default. Every host supplies projectId, themePreference,
locale, resource, pageLocation, pageParams, and translations. Context without a
project, resource or page keeps that field undefined. pageParams defaults to {} and
translations have empty bundles when the host supplies none. Custom props remain supported.
lastCommand is deprecated; use client.events or refreshOn for refreshes.
Capability failures are Errors with code, message, and optional data. Narrow them with
isWebviewCapabilityError(error) from @pstdio/sdk/extensions. This works across bundles.
A declaration denial uses undeclared_webview_capability and data.capability. Invalid
parameters use invalid_params and keep nested validation issues. Command rejections retain
their separate CommandOutcomeError.outcome contract.
Declare bare capability names. Versioned declarations such as "clipboard.write@1" remain
accepted but are deprecated through 0.44. Typed clients still require the declarations they use.
client.placement.close() needs placement.close. Use notification.show for system notices in the status bar.
The compatibility method client.notify.toast({ type, title?, message }) uses the same host routing.
The older { level, title, message? } input shape is deprecated.
Terminal sessions
Use the host terminal surface for new views. The old terminal.session capability and
createTerminalSessionBridge remain supported but are deprecated in 0.44.
See terminal sessions for shell activity, ownership and cleanup.
Package Assets
Use packageAsset() for files shipped inside the extension package.
Template files are extension defaults, not host records. If users can edit them, declare a template type with list, read, save, and delete command refs. Keep overrides in ctx.storage and read untouched defaults through ctx.packageFiles. The dashboard discovers the type and calls those commands; it does not know the extension’s storage format.
The command values use these shapes:
list: returns{ name, title, type }[].read: accepts{ name }and returns{ name, title, type, content } | null.save: accepts{ name, title?, type, content }and returns the saved item.delete: accepts{ name }.
import { defineTemplate } from "@pstdio/sdk/extensions";
import { defineExtension, defineView, packageAsset } from "@pstdio/sdk/extensions";
export default defineExtension({
templates: [
defineTemplate({
id: "ticket",
title: "Ticket",
type: "ticket",
source: packageAsset("./templates/ticket.md", import.meta.url),
}),
],
views: [
defineView({
id: "planner",
title: "Planner",
body: {
kind: "webview",
entry: packageAsset("./webviews/planner.tsx", import.meta.url),
},
}),
],
});
Package asset paths must be relative and stay inside the package.
Command and hook handlers can read other packaged files through ctx.packageFiles. This API is read-only and scoped to the installed package root. Files omitted from an installed copy by .gitignore are unavailable at runtime.
Set pstdio.projectFiles.tracked in the package manifest to control the allocated ctx.extensionFiles repo mount. From 0.46 it is rooted at .pstdio/extension-storage/<publisher>.<name>/, the same folder as the extension’s artifact mounts. In 0.44 and 0.45 it is rooted at .pstdio/extension-storage/<package-name>/.publishers/<publisher>/. 0.46 does not move or read that folder. In 0.43.x it is rooted at .pstdio/ext/<publisher>.<name>/. Publishers with the same package name keep separate files and ignore rules. Unless tracked is true, the host adds an ignore entry for the extension’s full-ID folder on the first ctx.extensionFiles write, which also covers its artifact mounts. A write through an artifact mount alone does not add this entry.
Artifact mounts and storage
See artifact mounts and storage for records, assets, allocated files, webview reads and watched mounts.
Collection and file writes
These rules apply to 0.43.x and main:
ctx.storage.collection(name).list()returns a plain array of items,TItem[]. It is not{ items }or{ rows }. Map the items to rows yourself in a table or boardquery.get(id)returns the item, orundefinedwhen it does not exist.put(id, value)creates or replaces an item. Use it for new items.update(id, value)replaces only an existing item. It throws when the item does not exist, including when another writer deleted it, so a late edit cannot bring a deleted item back. Use it for edits instead ofgetfollowed byput.- On an artifact mount or
ctx.extensionFiles,writeText(path, value)creates or replaces a file.updateText(path, value)changes only an existing file. It fails when the file is missing and never recreates a file that was deleted during the write.
Save before you announce a change. In a command, validate the input, wait for the storage write to finish, then call ctx.events.emit(eventRef, payload), then return the saved value. Do not emit when the write failed. Views that list the event in refreshEvents run their query again, and webviews that subscribe read again, so they must find the data already saved. The event payload is a signal, not the data.
Webview reads
See webview mount reads.
Watched mounts
See watched mounts.
Client events and workspace scope
createWebviewClient also exposes page, files, navigation, placement, notices and preferences. Subscribe through the events client and dispose subscriptions when the view unmounts. Pass { workspaceId } when commands need a specific workspace; omitted commands use the project’s default workspace. The client defaults to the host’s calling extension ID; a type-only import does not change routing. See the client contract for signatures and options.
Streamed commands
Declare the commands.stream webview capability to read a command that declares stream: streamOf<TChunk>():
const controller = new AbortController();
const stream = client.streams["logs.tail"]({ source: "build" }, { signal: controller.signal });
for await (const line of stream) {
appendLine(line);
}
const outcome = await stream.outcome;
if (outcome.ok) showSummary(outcome.value);
else showFailure(outcome);
client.streams contains only commands with a stream declaration. It accepts the same parameters as client.commands, followed by an optional { signal }. Each stream has one consumer. outcome always resolves with the complete final outcome, including rejection and transport failure. The chunk iterator closes normally on each terminal path. Use getCommandValue(outcome) when a value or CommandOutcomeError is more useful. The old .result promise is deprecated and keeps its value-or-throw behavior through 0.44.
Call stream.cancel(), abort the signal, or break the loop to stop the command. Cancellation clears unread chunks, ends iteration and resolves an error outcome with command_stream_cancelled; it does not wait for a remote acknowledgement. Cancellation before start opens no subscription. Frame disconnect also cancels streams and plain command calls. Hidden mounted panels keep running. A lost connection resolves an error outcome with command_stream_disconnected and its original cause. It never retries the command.
HTTP SDK callers use client.extensions.streamCommand(projectId, commandId, input?, options?) with the same chunks, outcome and cancellation rules. The old HTTP extensions.stream event iterator stays callable and is deprecated.
The host allows 16 live streams per frame and 8 MiB of unread JSON per stream. Overflow ends the stream with command_stream_overflow. All command streams and session readers share one connection. Events remain invalidation signals; chunks go only to their caller.
The low-level commands.stream bridge accepts start, cancel, and ack operations. createWebviewClient handles IDs, consumed-byte acknowledgements, and scoped data/end events for you.
Local editing sessions
On main for API 0.4.0, client.editing.openCommand(options) joins host-owned
command editing for the calling project, extension and document key. Its declared
read sources return full values or patches; semantic commands, stable operation
IDs and acknowledged previews share one authoritative owner across views.
See the shared-state author guide
for result envelopes, read coverage and required-write retirement.
To try the API, run bun run --cwd packages/pstdio-workbench canvas and open
Reference → Extension API → Shared editing sessions → Playground. Hold and release saves,
edit either shared view, preview or cancel a move, and fail a held save to test retrying.
The story uses the real SDK and host session with in-memory transport and persistence.
On main (extension API 0.2.1, after release 0.44.0), declare editing.session and use
client.editing.open when several webviews edit the same document. The host keeps one local
session for the calling project, extension and key. Views receive edits before a backend save
finishes. The session keeps one save queue and combines pending field changes while a write
is in flight. This is local workbench state; it is not cross-device synchronization or durable storage.
const session = await client.editing.open({
key: documentId,
initial: await client.commands["document.read"]({ documentId }),
save: {
commandId: `${host.extensionId}.command.document.save`,
params: { documentId },
},
});
const unsubscribe = session.subscribe(() => showDocument(session.getSnapshot().value));
await session.commit([{ path: ["title"], value: "New title" }]);
The save command receives its fixed params plus a changes array. It must belong to the
calling extension, apply the complete batch before announcing success, and return only after saving. Use
applyEditingChanges in that command and diffEditingState to compare JSON objects. Both
helpers are exported from @pstdio/sdk/extensions. Paths traverse objects and set fields; an empty path replaces
the root object. Replace arrays as a whole. Changes can replace arrays or objects, including removing old properties.
Prototype paths and non-object roots are rejected.
session.getSnapshot() returns value, version, revision and savedRevision. version
orders every local update. revision counts committed edits; savedRevision advances only
after a successful write. A save failure retains the edit. session.save() retries or awaits
the shared queue. A commit promise waits for the queue, while subscriptions update immediately.
Keep errors beside the initiating control.
Use session.preview(changes) during a gesture. Successive previews add to that view’s draft
and appear in every participating view without saving. session.commit() commits that draft
once; session.cancel() removes it without a write. Other views’ drafts remain separate.
Keep view-only selection, active tool, scroll and zoom outside the durable document.
diffEditingState builds patches and applyEditingChanges applies a batch atomically to a JSON object.
rebaseEditingChanges(value, drafts) composes a map of independent patch batches and drops
batches whose paths no longer apply. Extension-owned persisted patch stores can use that
same rule to keep parent replacements readable when concurrent child patches arrive.
Subscribe to the extension’s saved-change event and call
session.refresh(() => client.commands["document.read"]({ documentId })) for backend or agent
edits. Refresh waits for pending saves and repeats the backend read if shared state changed while reading.
Events remain invalidation signals. Do not publish document data through lastCommand.
A structural commit or refresh cancels drafts whose paths no longer apply.
On disposal, unsubscribe and call session.close(). Closing a view cancels its preview and
revokes its connection. Pending saves belong to the document and continue after a view closes.
The host drops a clean session after its final view closes; reopening reads durable state.
Unsaved state remains local to the live workbench after a failure and is lost if that workbench
is destroyed. A late view joins the current session instead of replacing it with its older read.
The low-level editing.session bridge accepts open, commit, preview, cancel, refresh,
save and close. The SDK manages connection IDs, edit sequences, subscriptions and stale replies.
A stale low-level refresh returns no snapshot; the SDK retries the backend read.
Sessions cannot choose another project or extension, and an open key must use the same save command.
Global views without a project do not provide this capability. Publish SDK and host support before
adopting it in separately released extensions.
Shared text sessions (unreleased)
Shared text uses editing.text and client.editing.text, separately from the
structured editing sessions above. A source owner declares a defineTextSource
provider and returns its textDocument reference from a file view. The view can
select an installed text editor with textEditor; omission selects native Markdown.
An editor can open the selected document with await client.editing.text.open({ selected: true }). This admits the member and returns the initial collaborative snapshot in one request on a new placement. The host checks the selection and current write permission. An editor can also open its own source reference or the opaque grant from
client.editing.text.current(). A grant cannot open an unselected foreign source.
client.editing.text.open(input) returns a public text session. Its snapshot contains
the Yjs text, historyId, current editable and closing permissions, pending,
connected, friendly participants and an optional typed error. Import the matching
Yjs 13 runtime normally. Use session.transact for local changes, or public Yjs
transactions with session.origin. Remote changes must not become new local edits.
session.flush() captures the current authored prefix and waits for local host
durability. session.project() also waits for that prefix’s source projection.
Neither means cloud catch-up has finished. A failed projection retains acknowledged
text. session.retry() retries recoverable work without changing its source lifetime.
Bindings that queue renderer changes register session.beforeReceive(handler).
The handler synchronously drains those existing edits before incoming snapshots,
including acknowledgement and recovery snapshots, can change the binding’s history.
It may run when text is unchanged. Do not await work or author a fresh edit on every
notification. The returned function removes the handler. A thrown handler leaves
the incoming snapshot available for retry; recursive receive and async handlers are
rejected. Normal remote edits preserve local undo. When historyId changes, reset
the old undo stack and selection anchors while retaining SDK-owned drafts.
On main, after 0.46.0 (API 0.3.1), handlers receive an optional context with
textChanged, historyChanged and editableChanged. When all three are false,
a renderer may keep its queued typing until its normal publication boundary.
Every handler still runs for every ingress. Missing context requires the usual
synchronous drain. Text changes include CRDT deletions and replacements even when
the visible string is unchanged; permission and history transitions keep their barriers.
Use session.createDraft() for tentative composition and table edits. A draft owns
its original causal history; commit() freezes and admits that delta, and retries
the same submission. cancel() discards an unsubmitted draft, or one definitively
refused as read only without an earlier uncertain admission. Retired-source recovery
also allows explicit cancellation. Unknown admission and acknowledged edits cannot
be undone by cancelling a draft. Register session.beforeClose(handler) to finish or explicitly
cancel local drafts. An unfinished draft blocks ordinary close and keeps its recovery
data available. session.close() waits for finalized authored edits to become durable.
Authenticated HTTP consumers use
client.textEditing.connect, then the public guest
adapter and createTextEditingClient. Both routes share source admission, frame
validation and durability. These additions require matching unreleased host and SDK
support before adoption by separately released extensions.
Page params
Page params are on main (extension API 0.1.7 and later) and ship in the release after 0.43.x. @pstdio/sdk 0.43.1 and the 0.43.1 app do not have them.
A page can declare a params record. Each definition has a type: string, number, boolean, or string[]. It may have a matching default. String definitions may also restrict values with values.
Names match ^[a-z][a-z0-9-]*$, contain at most 64 characters, and cannot use existing host URL selectors: resource, section, document, line, column, endLine, or endColumn. A page may declare 32 names. Its encoded param query is limited to 2,048 characters.
Every webview receives pageLocation and pageParams props. pageLocation.params contains overrides that differ from defaults. pageParams fills in declared defaults. Read the same store through client.page.location(), client.page.params<T>(), and client.page.subscribe(listener). The render-context page helper is deprecated.
Declare page.params.update to call client.page.updateParams({ range: "now-6h" }). A null value resets that name to its default. The host replaces the current history entry and sends the location to every view. Only the extension that owns the active page can update it. Other callers fail with page_params_not_owner; calls without a page fail with page_params_no_page.
A page navigation target may carry params. It replaces all destination params and pushes history when the location or params change. Undeclared names, wrong types, disallowed string values, and oversized queries fail with page_param_invalid. The previous location, URL, history, and layout stay intact. Invalid URL values are ignored and use their defaults instead.
URLs use plain query keys. Lists use repeated keys in item order. Missing values use their defaults. Defaults and empty lists are omitted, so an empty list reads as its declared default. Params stay out of route identity, page state keys, layout caches, and breadcrumbs. Saved locations and contextual parents retain their own params.
Native query and file-load callbacks receive defaults through renderer.pageParams for placements owned by the active page. The host reruns these reads when params change. Shared shell and mode placements do not inherit page params.
Webview preferences
Declare preferences.get and preferences.set to save small view choices:
await client.preferences.set("lastRange", "now-6h");
const range = await client.preferences.get("lastRange");
On main, API 0.4.2 adds client.preferences.query(name, scope?) under preferences.get. Its readonly query data is {value}: a loaded missing choice has value: undefined, while unread data is undefined. The host retains accepted choices across guest recreation, scopes invalidation to the effective preference project and keeps required client.preferences.set writes ordered after the guest closes. Observe through useWebviewCommandQuery; save through set, without publishing a second local snapshot. Publish the supporting host and SDK before independent adoption.
An undeclared name belongs to the calling extension. Other extensions have separate values under the same name. Dashboard webviews store these values on the server, so browser reloads and Desktop restarts keep them, and other clients read the same values. set returns only after storage succeeds.
The default scope is user, shared by clients of the runtime. project uses the active project when scopeId is omitted. workspace and session require scopeId. extension uses the calling extension’s user scope. Scoped reads fall back to the user value. default is read only and has no value for an undeclared name. Writing it fails with preference_scope_read_only.
Each JSON value may contain 16 KiB. An extension may store 256 KiB across all scopes. Writes exceeding either limit fail with preference_too_large and preserve stored values. Removing an extension retains its preferences for a later reinstall.
dashboard.themePreference and dashboard.locale remain shared host names with their existing provider behavior. Access to names registered by another extension still works, but emits a deprecation warning. Use your own extension’s preference names; cross-extension access is deprecated in 0.44 and will be removed in 0.45. Shared core preferences remain supported.
Agents use the same authenticated API:
GET /v1/projects/{projectId}/extensions/{instanceId}/preferences/{name}reads{ name, value? }.PUTto the same path writes a JSON body{ "value": ... }and returns{ name, value }.- Optional query keys are
scopeandscopeId. - Global views use
/v1/extensions/installed/{installName}/preferences/{name}. Project, workspace, and session scopes need an explicitscopeIdon this path.
These routes store extension-owned values. Declared settings use the settings API. Theme and locale remain host appearance choices. Use ctx.storage for extension product data rather than view preferences.
Updated at: 2026-11-09