Desktop API

Desktop API

Desktop API

Function

bt_app injects window.bt into the static, server and remote pages. The desktop API provides BT backend calls, window control, system dialogs, tray, clipboard, screen straw, frame selection screenshots, global shortcut keys, notifications, file drag-in, directory file monitoring, application information, as well as bounded streaming HTTP, application credentials, workspace, native processes and application-owned data capabilities. The

page should only use window.bt. The runner will not expose the global window.__TAURI__, nor will it expose the local fs, net, and process capabilities directly to the front end.

Syntax

All asynchronous methods return Promise. Data is returned directly on success; Promise will reject on failure, and the error value is a string or an error object that can be converted to a string.

Parameters

bt.call

ParameterTypeRequiredDescription
namestringYesGlobal function name in main.bt
...argsanyNoParameters passed to the BT function will be converted according to JSON value

bt.window

MethodParametersReturn valueDescription
set_titletitle:stringvoidSet window title
set_sizewidth:number, height:numbervoidSet the logical size of the window
set_positionx:number, y:numbervoidSet the logical coordinates of the upper left corner of the window frame, supporting negative coordinates for multiple monitors
placementNoneobjectRead the logical coordinates and dimensions of the window frame and the available workspace of the current monitor
set_background_colorcolor:stringvoidSet the background color of the window and WebView; color must be #RRGGBB
set_resizableresizable:booleanvoidSet whether resizing is allowed
minimize / maximize / restore / close / hide / show / focus / centerNonevoidCommon window actions
set_fullscreenfullscreen:booleanvoidSet full screen
is_fullscreen / is_maximized / is_minimized / is_visible / is_always_on_topNonebooleanRead window status
set_always_on_topenabled:booleanvoidSet the window to be on top
set_decorationsvisible:booleanvoidSet the system title bar and border
set_skip_taskbarenabled:booleanvoidSet whether to skip the taskbar
set_close_modemode:stringvoidexit, hide or tray
on_close_requestedcallback:functionfunctionTake over the exit mode close request and return the cancel listening function
close_nowNonevoidRelease and close the window after the page completes asynchronous closing
dragNonevoidCustom title bar drag window
start_resizeedge:stringvoidtopbottomleftrighttop_lefttop_rightbottom_leftbottom_right
flashNonevoidRequest the system to remind the user to pay attention to the window
open_devtoolsNonevoidOpen WebView developer tools, only available when dev.devtools=true

set_background_color() simultaneously updates the opaque background color of the native window and WebView, which is suitable for switching between light and dark themes for ordinary windows. When HTML rounded corners, PNG Alpha, or a transparent page background are required, window.transparent=true should be set during app.json creation. This runtime method cannot be used in place of a transparent window configuration.

x and y of set_position(x, y) use logical pixels; negative numbers can be passed when multiple monitors are located on the left or above the main screen. placement() return fields:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
xintegerYesNoneLogical pixel, can be negativeX coordinate of the upper left corner of the window frame
yintegeryesnonelogical pixel, can be negativeY coordinate of the upper left corner of the window frame
widthintegeryesnonegreater than 0window frame width
heightintegeryesnonegreater than 0window frame height
scale_factornumberYesNoneGreater than 0The scaling factor of the current display from logical pixels to physical pixels
content_areaobjectYesNoneSee table belowWebView content area after deducting system borders and shadows
work_areaobjectYesNoneSee the table belowThe available work area of the current monitor after deducting the system area such as the taskbar

Both content_area and work_area use the same rectangular field; the former is the WebView content area on the desktop, and the latter is the available workspace of the current monitor:

ObjectFieldTypeRequiredDefault valueValid range or optional valueMeaning
content_areaxintegeryesnonelogical pixel, can be negativeX coordinate of the upper left corner of the content area
content_areayintegeryesnonelogical pixel, can be negativeY coordinate of the upper left corner of the content area
content_areawidthintegeryesnonegreater than 0content area width
content_areaheightintegeryesnonegreater than 0content area height
work_areaxintegeryesnonelogical pixel, can be negativeX coordinate of the upper left corner of the work area
work_areayintegeryesnonelogical pixel, can be negativeY coordinate of the upper left corner of the work area
work_areawidthintegeryesnonegreater than 0work area width
work_areaheightintegeryesnonegreater than 0work area height

bt.dialog

MethodParametersReturn valueDescription
open_fileoptionsstring or nullselect a single file
open_filesoptionsstring[]Select multiple files
open_diroptionsstring or nullselect directory
save_fileoptionsstring or nullselect save path
messagemessage:string, optionsvoiddisplay message box
confirmmessage:string, optionsbooleanShow confirmation box

options.title is the dialog box title, options.default_path is the default path, and options.filters is the file filter array. Message box options.kind supports info, warning, and error.

bt.tray

MethodParametersReturn valueDescription
enableoptionsvoidEnable the tray icon, repeated calls will update the existing tray
disableNonevoidClose tray icon
set_iconicon:stringvoidSet tray icon path
set_tooltiptext:stringvoidSet tray tip
set_menumenu:arrayvoidSet tray menu
on_menu_clickcallbackfunctionMonitor menu click and return to cancel listening function

The menu item format is {id:'show', text:'Show Window', enabled:true}; the separator format is {type:'separator'}. The same application retains one tray icon by default. Repeated calls to window.bt.tray.enable() update the icon, tooltip, and menu without adding duplicate tray entries.

window.bt.window.set_close_mode('tray') only sets the behavior of the window close button: when the user clicks the window close button or the code calls window.bt.window.close(), the window will be hidden in the tray and the program will continue to run permanently. If you need to close to the tray immediately after clicking the button, you should set the tray mode first and then call window.bt.window.close().

on_close_requested() is used for applications that must wait for asynchronous disk placement before exiting. After registration, the shutdown request of exit mode will be blocked first and the callback will be called; close_now() must be called after the callback completes the save. If the save fails, the application can keep the window and prompt the user, but cannot call close_now(). Canceling listening will restore the default direct shutdown behavior.

bt.clipboard

MethodParametersReturn valueDescription
read_textNonestringRead text from clipboard
write_texttext:stringvoidwrite text
clearNonevoidClear the clipboard

bt.screen

MethodParametersReturn valueDescription
pick_coloroptionsColorResult or nullCapture each monitor screen before the mask appears, display the Tauri transparent straw mask; preview the pointer pixels in real time when moving, left click to return to color, Esc or right click to return null
capture_areaoptionsCaptureResult or nullCapture the screen of each monitor before the mask appears, drag the frame to select the area within a single monitor; if successful, it can be written directly to the system image clipboard

options fields of pick_color(options):

FieldTypeRequiredDefault valueValid range or optional valueMeaning
copy_to_clipboardbooleanNotruetrue or falseWhether to write uppercase #RRGGBB to the text clipboard after success

options fields of capture_area(options):

FieldTypeRequiredDefault valueValid range or optional valueMeaning
copy_to_clipboardbooleanNotruetrue or falseWhether to write the RGBA image directly to the system picture clipboard after success

ColorResult field:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
xintegerYesNonePhysical pixel coordinates of the virtual desktop, which can be negativeX coordinate of the color point
yintegerYesNonePhysical pixel coordinates of the virtual desktop, which can be negativeY coordinate of the color point
rintegeryesnone0~255red channel
gintegeryesnone0~255green channel
bintegeryesnone0~255blue channel
aintegerYesNone0~255Alpha channel, the screen is usually 255
rgbintegerYesNone0~1677721524-bit binary color value, calculated according to (r << 16) | (g << 8) | b
hexstringyesnone#RRGGBBFixed uppercase hexadecimal color value
rgbainteger[]YesNone4 bytes from 0 to 255Fixed order [r, g, b, a]
clipboardbooleanyesnonetrue or falseWhether the text has been written to the clipboard this time

CaptureResult field:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
xintegerYesNonePhysical pixel coordinates of the virtual desktop, which can be negativeX coordinate of the upper left corner of the selection
yintegerYesNonePhysical pixel coordinates of the virtual desktop, which can be negativeY coordinate of the upper left corner of the selection
widthintegeryesnoneat least 2 physical pixelsselection width
heightintegeryesnoneat least 2 physical pixelsselection height
clipboardbooleanyesnonetrue or falseWhether the system picture clipboard has been written to this time

The screen image is returned to the front end without passing through Base64 or JSON array; the native layer directly writes RGBA to the system image clipboard, so it can be pasted in chat boxes, rich text editors and image software that support image pasting. Plain text input boxes or software that actively disables image pasting cannot accept images.

bt.shortcut

MethodParametersReturn valueDescription
registershortcut_id:string, accelerator:string, callback:functionfunctionRegister or replace a system global shortcut key, return the asynchronous cancellation function after Promise is completed
unregistershortcut_id:stringbooleanUnregister the specified ID; it exists and returns true if the cancellation is successful
unregister_allNonevoidUnregister all shortcut keys registered by the current application through bt.shortcut

register() parameters:

ParametersTypeRequiredDefault valueValid range or optional valueMeaning
shortcut_idstringYesNone1 to 64 letters, numbers, - or _Stable shortcut key ID used by the page
acceleratorstringYesNoneTauri shortcut key combination, such as CommandOrControl+Alt+COperating system global shortcut key
callbackfunctionYesNoneJavaScript functionCallback after shortcut key is pressed

Callback payload fields:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
shortcut_idstringyesnonestable ID at registrationtrigger source
acceleratorstringyesnoneaccelerator text of successful registrationcurrent key combination

A maximum of 16 global shortcut keys can be registered for the same application. The same shortcut_id will atomically replace the original combination; the same combination cannot be bound to two IDs at the same time. The shortcut key is held by the application process and can still be triggered after the main window is hidden or closed to the tray; it will be released by the operating system when the application exits. When the page is actively deactivated, the returned logout function or unregister_all() should be called.

bt.notify

MethodParametersReturn valueDescription
permission_stateNonestringgranted, denied, or prompt
request_permissionNonestringRequest notification permission
showoptionsvoidshow notifications

When options.title is empty, the application title is used, and options.body is the notification body.

request_permission() returns the system notification permission status; show() actually sends system notifications. Windows portable exes use a compatible toast delivery path and do not rely on app notification registration created by the installer. Whether a notification pops up on the desktop banner is still determined by the operating system notification settings, Do Not Disturb mode and application notification policy. If it does not pop up, it can usually still be viewed in the system notification center.

bt.drag

MethodParametersReturn valueDescription
on_filescallbackfunctionListen for dragged files or directories, the callback parameter is an absolute path array

bt.app

MethodParametersReturn valueDescription
versionNonestringCurrent application version
engine_versionNonestringbt_app engine version
platformNonestringwindows, macos, linux or other system name
open_urlurl:stringvoidOpen the HTTP/HTTPS address with the system default browser
open_pathpath:stringvoidOpen the file or directory with the system default program
reveal_pathpath:stringvoidLocate path in file manager
quitNonevoidExit program
argsNonestring[]The current software business parameters of the bt_app command, BTR path and -- have been eliminated
infopath:stringBtrAppInfoRead the app.json, container information and icon of BTR software without executing the software code
runpath:string, args:string[]BtrRunResultStart an independent BTR software process using the current bt_app
documents_dirNonestringThe absolute path of the user's "documents" known directory after parsing by the operating system
watch_pathpath:string, callback:function, optionsfunctionMonitor directory file changes and return to cancel the listening function
unwatch_pathNonevoidStop all monitoring of the current window

path of info(path) must be an absolute or canonical path to an existing .btr file. It will complete the BTR format, version, resource path and size limit verification, only read btr.json, app.json and optional icons, and will not execute app.main, server.bt or page scripts. It is suitable for toolbars to safely display software information. app.icon currently only supports ICO, so icon_data_url uses data:image/x-icon;base64,...; when not configured or does not exist, it is null.

BtrAppInfo field:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
pathstringyesnonecanonical absolute .btr pathactual software file to check
idstringyesnonelegal app.idstable application identification
namestringyesnonelegal app.nameapplication internal name
titlestringyesnonenon-empty textdefault display title
versionstringyesnonenon-empty textapplication version
descriptionstring or nullyesnulltext or nullapplication description
modestringyesnonestatic, server, remoteoperating mode
entrystringYesNoneVerified entryPage entry
iconstring or nullYesnullICO relative path within the project or nullapp.json original icon path
icon_data_urlstring or nullYesnullICO data URL or null; maximum icon size 16 MiBIcon that can be directly assigned to <img src>
format_versionintegerYesNoneCurrently 1BTR container format version
bt_versionstringyesnoneBT versionRuntime version to generate BTR
bt_min_versionstringyesnoneBT versionMinimum runtime version declared by the software
file_countintegerYesNone0~4095Number of resources excluding internal btr.json
package_bytesintegerYesNoneMaximum 256 MiBNumber of bytes in the compressed file
uncompressed_bytesintegerYesNoneMaximum 512 MiBTotal number of bytes after expansion of all entries

run(path, args=[]) will completely verify the BTR again before starting the child process, and create the process directly with the parameter array without going through the shell. args has a maximum of 256 entries, and a single entry has a maximum length of 32768 bytes. Promise completion only means that the operating system has created the process, not that its WebView has completed page loading.

BtrRunResult field:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
pidintegeryesnoneoperating system process IDcreated BTR software process
pathstringyesnonecanonical absolute .btr pathactual running software file
idstringyesnonelegal app.idstable identification of the running software

Each time run() creates an independent software process to isolate the VM, window, tray, shortcut keys and exit life cycle from each other; it solves the disk volume problem of multiple software repeatedly carrying bt_app exe, and does not promise that multiple running software can share the same WebView process. Built-in toolbar capabilities such as eyedroppers and screenshots can remain in the toolbar process, and their windows are only created when the BTR software is actually started.

documents_dir() uses the system-known directory API, does not hardcode the Documents name, and is compatible with localization, OneDrive, and system redirections. watch_path() uses system file events to monitor directory changes and does not scan the directory at a fixed period; the same window can retain up to 64 listeners at the same time. options.recursive defaults to true, which means recursively listening to subdirectories. The callback parameter is {watch_id, root, kind, paths}, kind may be create, modify, remove, rename or other. Generally, the cancellation function returned by watch_path() should be saved and there is no need to use the internal watch_id directly.

bt.credential

App credentials are saved as clear text JSON to the current user's hidden app directory. Use this stable identifier when explicitly configuring app.id; when not configured, continue to use app.name for compatibility with older versions, such as %USERPROFILE%\.bt_ai\credentials\. This is a clear text format that facilitates migration and manual maintenance and does not use Windows DPAPI. The interface does not provide the page with a method to read clear text, but native programs with access to the user's directory can read the file, so the caller must explicitly prompt in the interface and protect operating system account permissions.

MethodParametersReturn valueDescription
storecredential_id:string, secret:stringvoidSave credentials atomically as JSON plaintext; same ID will overwrite old files
hascredential_id:stringbooleanDetermine whether the credential JSON exists, the format is valid and the ID matches
deletecredential_id:stringbooleanDelete the specified credential; returns whether it is actually deleted

FieldTypeRequiredDefault valueValid range or optional valueMeaning
credential_idstringYesNone1~128 characters, only letters, numbers, _, -, .Stable credential ID defined by the caller, file name is <credential_id>.json
secretstringyesnone1~4096 UTF-8 charactersapi_key plain text field saved to JSON, read briefly during native request construction

bt.http

stream() initiates a real asynchronous HTTP request, and returns response headers, SSE or normal chunks, and finally the complete body through callbacks. Event monitoring will be installed before startup; cancel() will first close the native event gate and then notify the network task to terminate, so the status or body events of the request will not be distributed after successful cancellation.

stream options FieldTypeRequiredDefault valueValid range or optional valueMeaning
request_idstringNoAutomatically generate UUID1~128 characters, only letters, numbers, _, -, .Unique request ID that can be specified when the caller needs to pre-correlate events
urlstringyesnonehttp:// or https://request address
methodstringNoPOST1~16 ASCII lettersHTTP method
headersobjectNo{}Maximum 32 items; name cannot exceed 128 characters, value cannot exceed 8192 charactersNon-sensitive request headers; authorization, proxy-authorization, and cookie are prohibited
bodystringNo""UTF-8 bytes no more than 4 MiBRequest body
credential_idstringNo""Null value or valid application credential IDIf not empty, the native layer will read JSON and inject Authorization: Bearer ..., and the page will not be returned
timeout_msintegerNo1200001000~600000Timeout milliseconds for the entire request
max_response_bytesintegerNo40000001~4000000The maximum number of accumulated bytes allowed in a single response

stream() returns the control object:

The native layer will initialize the Rustls ring crypto provider idempotently before constructing the first HTTP client. Therefore, even if the application calls window.bt.http.stream() directly after a cold start, it does not rely on the BT standard library or web services to perform network initialization in advance.

FieldTypeRequiredDefault valueValid range or optional valueMeaning
request_idstringYesNoneThis request IDThe stable ID corresponding to the event
active_limitintegerYesNoneCurrently fixed at 8The upper limit of concurrent streaming requests allowed by the current process
max_response_bytesintegerYesNone1~4000000The actual upper limit of the response for this request
offfunctionyesnoneno parametersonly cancels page event monitoring, does not terminate the request
cancelfunctionyesnoneno parameters, returns Promise<boolean>atomically closes the event gate and cancels the request

Streaming callback event fields:

FieldTypeRequiredDefault valueValid range or optional valueMeaning
request_idstringYesNoneThis request IDRequest association ID
sequenceintegeryesnonestrictly increasing from 1single request event sequence
kindstringyesnonestart, headers, chunk, done, error, cancelledevent type
statusintegerYes00 or HTTP status code0 if no response headers have been received
datastringYes""Single chunked text or final full textText data for chunk and done
messagestringYes""Desensitization error textStatus description of error and other events
received_bytesintegerYes00~the upper limit of this responseThe current cumulative number of response bytes

A single response can dispatch up to 16384 chunked events; exceeding the upper limit of the number of bytes or chunks will end with error and release the request registration.

bt.workspace

The workspace API first registers a real directory, and then uses the short-term workspace_id to operate the relative path. All paths are normalized and true path bounds checked, recursive lists do not follow symbolic links or junctions.

MethodParametersReturn valueDescription
openroot:stringWorkspaceOpenResultRegister existing real directories; a maximum of 8 entries will be retained, and the oldest registration entry will be eliminated if the limit is exceeded
closeworkspace_id:stringbooleanClose registration without deleting any files
listworkspace_id:string, relative:string, recursive:booleanWorkspaceEntry[]Bounded list of directories, up to 4096 entries
readworkspace_id:string, relative:string, max_bytes:integerWorkspaceReadResultRead UTF-8 text, max 4 MiB
atomic_writeworkspace_id:string, relative:string, content:string, expected_sha256:string|nullWorkspaceWriteResultAtomic replacement of temporary files in the same directory, and concurrent overwriting can be rejected based on the old summary

Calling fieldTypeRequiredDefault valueValid range or optional valueMeaning
rootstringYesNoneExisting absolute directoryThe real root directory of the workspace
workspace_idstringYesNoneID returned by open()Native workspace registration
relativestringlist no; read/write yes""relative path within the workspace; absolute paths and ..target directory or file are prohibited
recursivebooleanNofalsetrue or falseWhether to list directories recursively
max_bytesintegerNo10485761~4194304Reading upper limit, if exceeded, it will be rejected instead of truncated
contentstringwrite yesNoneUTF-8 textNew content written atomically
expected_sha256string or nullnonull64-bit hexadecimal SHA-256When non-null, only old files with the same digest are allowed to be overwritten

Return ObjectFieldTypeMeaning
WorkspaceOpenResultworkspace_idstringNatively generated short-lived workspace ID
WorkspaceOpenResultrootstringnormalized real root directory
WorkspaceEntrypathstringWorkspace relative path using /
WorkspaceEntrykindstringfile, directory or symlink
WorkspaceEntrybytesintegerNumber of bytes in the file; 0 for directories and links
WorkspaceReadResultpathstringcanonical relative path
WorkspaceReadResultcontentstringUTF-8 text
WorkspaceReadResultbytesintegerOriginal number of bytes
WorkspaceReadResultsha256stringContent SHA-256
WorkspaceWriteResultpathstringcanonical relative path
WorkspaceWriteResultbytesintegerNumber of bytes of new content
WorkspaceWriteResultsha256stringNew content SHA-256
WorkspaceWriteResultprevious_sha256string or nullSummary of old content; null for new files

bt.process

The native process is started directly using the program name and parameter array, without going through the shell. The process must belong to a caller task and registered workspace; when querying and stopping, it must match process_id, task_id and the unforgeable identity. Stopping will clean up the process tree corresponding to the handle and end external processes in batches without naming them.

start options FieldTypeRequiredDefault valueValid range or optional valueMeaning
task_idstringyesnonelegal short-term IDcaller task ownership
programstringyesnonenon-empty, up to 32768 charactersexecutable program path or program name
argsstring[]No[]Maximum 256 items, maximum single item 32768 charactersParameter array without shell
workspace_idstringyesnoneregistered workspace IDprocess directory boundary
cwdstringNo""Relative directory that already exists in the workspaceCurrent directory of the child process
environmentobjectNo{}Up to 64 items; the longest name is 256, the longest value is 32768Only the environment variables of the child process are injected, and the process snapshot is not written
timeout_msintegerNo00~864000000 means no automatic timeout; otherwise, the process tree will be cleaned up upon expiration
output_limitintegerNo655361~1048576The upper limit of tail bytes reserved by stdout and stderr respectively

ProcessSnapshot fieldTypeRequiredDefault valueValid range or optional valueMeaning
idstringyesnonenative record IDprocess_id of status() / stop()
task_idstringyesnonestartup valuecaller task ownership
identitystringyesnone64-bit digestProcess identity value required for exact stop
pidintegeryesnoneoperating system PIDfor observation only, not a replacement for identity
programstringyesnonestartup valueprogram text
argsstring[]Yes[]Startup valueParameter array; sensitive credentials must not be passed as parameters
cwdstringYesNoneThe real directory in the workspaceThe actual current directory
runningbooleanyesnonetrue or falseIs it still running
exit_codeinteger or nullyesnullnull while runningexit code
timed_outbooleanYesfalsetrue or falseWhether terminated by timeout
stdout / stderrstringYes""Each does not exceed output_limitBounded output tail
stdout_dropped / stderr_droppedintegeryes0greater than or equal to 0number of bytes dropped due to upper limit
started_atintegeryesnoneUnix millisecond timestampstartup time

The on_event() callback field is process_id:string, task_id:string, kind:string, data:string, pid:integer; kind can be start, stdout, stderr, exit, timeout or stopped. A maximum of 32 processes can be registered at the same time, and the end records will be eliminated according to the startup time.

bt.data

The application JSON status is saved in the sessions subdirectory under the current user's hidden application directory by default. Use the stable flag when explicitly configuring app.id; when not configured, continue to use app.name for compatibility with older versions. Automated acceptance can set BT_APP_DATA_HOME to temporarily place the hidden application directory in the specified parent directory; normal desktop operation should keep this variable unset. Cleaning adopts the three-step boundary of "preview - user secondary confirmation - one-time ticket execution". Only the fixed subdirectory of the application data root is cleaned, and the registered workspace is not accessed.

MethodParametersReturn valueDescription
storekey:string, value:any JSONvoidAtomicly save a JSON file
loadkey:stringany JSON or nullreturns null if the file does not exist
prepare_cleanupNoneCleanupPreviewCount fixed categories and generate a one-time confirmation ticket valid for 120 seconds
confirm_cleanupconfirm_token:stringCleanupResultConsume the ticket and actually clean it; tickets that are incorrect, expired or reused are rejected

Calling fieldTypeRequiredDefault valueValid range or optional valueMeaning
keystringstore/load YesNone1~64 characters, only letters, numbers, _, -Application JSON file key
valueJSONstore yesnoneno more than 4 MiB after serializationapplication state value
confirm_tokenstringconfirm_cleanup YesNoneprepare_cleanup returned and not consumed, not expiredSecond confirmation ticket

Return ObjectFieldTypeMeaning
CleanupPreviewconfirm_tokenstringOne-time ticket valid for 120 seconds
CleanupPreviewcategoriesCleanupCategory[]Fixed cleaning category statistics
CleanupPreviewtotal_filesintegerTotal number of files
CleanupPreviewtotal_bytesintegerTotal number of bytes
CleanupPreviewboundarystringDescription of the boundary of the real directory being cleaned this time
CleanupCategorynamestringknowledge_cache, sessions, logs, temp or credentials
CleanupCategoryfilesintegerNumber of category files
CleanupCategorybytesintegerTotal number of bytes in category
CleanupResultclearedstring[]Fixed category processed
CleanupResultremoved_filesintegerNumber of files before cleaning
CleanupResultremoved_bytesintegerNumber of bytes before cleaning
CleanupResultworkspace_untouchedbooleanAlways true when the current implementation is successful, indicating that the user's workspace has not been touched

bt.events

on_backend(callback) listens to the bt.call() completion event and returns to the cancel listening function. The callback fields are as follows; the event does not contain the BT function return text.

FieldTypeRequiredDefault valueValid range or optional valueMeaning
namestringyesnonecalled BT global function namecalling source
okbooleanyesnonetrue or falseWhether the IPC call was successful
atintegeryesnoneUnix millisecond timestampcompletion time

Return Value

bt.call() directly returns the return value of the BT function. When the BT function returns an object, the front end receives a normal JSON object; when a string, number, Boolean or array is returned, the front end receives the corresponding JSON value.

If the BT function does not exist, an execution error is reported, the VM call queue is full, or the desktop API parameters are invalid, the Promise will reject and the {error,message,data} wrapper object will not be returned.

Code Examples

main.bt

Page call:

Screendropper, screenshots and global shortcut keys:

Tray menu:

Complete an asynchronous snapshot before exiting:

Read the user document directory:

Listen for directory changes:

Streaming request and real cancellation:

Workspace atomic update:

Notes

  • bt.call() is a long-term VM business channel; desktop capabilities such as windows, trays, clipboards, and notifications are independent command, does not occupy BT VM.
- The VM call queue is capped. The front-end should be throttled when making high-frequency calls to avoid uncontrolled growth.

- The remote page also has full window.bt capabilities and should only load trusted addresses.

  • The same window can retain up to 64 watch_path() monitors at the same time; each returned cancellation function only stops the corresponding monitor, and unwatch_path() stops all monitors when no parameters are passed.
  • on_close_requested() only intercepts the exit shutdown process of the window; the callback should prevent repeated execution, and close_now() can only be called after the asynchronous closing is completed.
- When BT_PERMISSION_DENY=desktop is set, windows, dialogs, trays, clipboards, global shortcuts, notifications, drag-in file events, file listen events, and app-level desktop commands are denied; screen eyedroppers and screenshots also require separate screen permissions. bt.call() itself is not restricted by desktop, and the standard library capabilities used internally by the called BT function are still checked according to their respective permissions.

- Windows, macOS and Linux X11 use the same set of Tauri self-drawn eyedroppers/box masks; macOS first use usually requires the user to grant screen recording permissions. Native Wayland does not support reliable global window coordinates and common global shortcut keys, the current version returns errors, and does not promise the same masking interface as X11.

  • The first version of screenshot selection is limited to a single monitor; multiple monitors each have a mask, but drag selection cannot be spanned from one monitor to another. HDR, Wide Color Gamut, Protected Video, and System Security Desktop may differ in color from the naked eye or return black content.
- Generic production API only provides boundary-constrained client HTTP, registered workspaces, and handleable subprocesses; does not expose arbitrary filesystem, network listening, shell strings, or kill-process-by-name capabilities.

- Credentials are clear text JSON in the current user directory and must not be placed in URLs, normal request headers, request bodies, process parameters, logs or page storage; credential_id should be used to allow native layer injection and restrict user directory access.

- Before closing an app, canceling a task, or clearing data, still-running streaming requests should be canceled and the child process of the task to which they belong should be stopped exactly.

- Common desktop API examples are located at examples/desktop-api; eyedropper, screenshot and global shortcut key examples are located at examples/desktop-screen-tools.