Files
sim/apps/desktop
Waleed f02ee99ce2 feat(desktop,cli): support self-hosted desktop installs (#7136)
* feat(desktop,cli): support self-hosted desktop installs

The desktop shell was already origin-agnostic at runtime — navigation, CSP,
cookie partition, and the update feed all derive from the configured origin,
and every deployment already serves /api/desktop/update/download and its
updater manifest. The one thing missing was a way to change that origin:
ConfigStore.setOrigin had no IPC channel, menu item, or UI behind it, so a
self-hoster installing the signed build was stuck on the baked default.

Adds the native server picker (Sim → Server…, plus a "Change server" button on
the offline page, since a shell pointed at an unreachable origin lands there
with nothing else to click). Its IPC family is gated to bundled file: senders:
the surface that repoints the shell must keep working when the current server
cannot be reached, and must never be drivable by a page that server serves.
A confirmed change relaunches rather than swapping in place — the origin keys
the cookie partition, update feed, encrypted per-origin task state, and every
live browser view and PTY.

Adds `sim-setup desktop`, which resolves the installer from the operator's own
deployment, checks that the update feed resolves too, and prints the server URL
to paste in. Documents the whole path under self-hosting, including the
build-your-own escape hatch for organizations with their own Developer ID.

* refactor(desktop,cli): review pass on self-hosted desktop support

Two real defects found while auditing the change for hardcoded assumptions.

`lastRoute` is a single global setting that carries a workspace id, so it
survived an origin change and opened /workspace/<old-id> on the new server.
resolveStartRoute cannot rescue that — it discards a route only on a confirmed
403, and a fresh partition draws a 401. Cleared on change, via a named list
that is now the documented home for deployment-scoped settings; the agent
browser's jar and its known-sites metadata are deliberately kept, together,
since changing deployments does not imply the account changed.

The offline page's "Check status" sent self-hosters to status.sim.ai, which
reports on Sim's deployments and is always green for theirs. Withheld for a
non-sim.ai origin, as is the same link in the Help menu, through one
isSimCloudOrigin predicate. Hiding it needed `button[hidden]{display:none}`:
the page's own `button{display:inline-flex}` is an author rule and outranks the
UA `[hidden]`, so the attribute alone left it rendering. The e2e offline test
now asserts the whole path, which covers the `server:` local-page IPC gate.

Review cleanups: setOrigin no longer rewrites settings when handed the origin
it already stores; the picker window installs a permission handler and pre-
paints its background like every other window, and its page is theme-aware so
that background is not a flash; the CLI reuses httpHealth and the
cross-platform openBrowser instead of reimplementing both, skips Compose/Helm
discovery when --url makes it dead, and folds two parallel switches into one
exhaustive one. Value-flag parsing is now one helper instead of a third copy.

* fix(desktop,cli): scope deployment capabilities to their origin

Changing the server left two device-global stores in place that grant the
INCOMING deployment authority the user only handed the outgoing one: local
filesystem grants (directories its agent may read, plus security-scoped
bookmarks) and the agent browser's cookie jar (live third-party sessions its
agent may drive). Sign-out clears exactly this pair; an origin change is the
same boundary, so it now clears it too — awaited before the relaunch, since a
quit racing an async clear could leave either behind. browserKnownSites goes
with the jar it describes, so Sim is never left believing in sign-ins the
profile no longer has.

The CLI printed the redirect's filename straight to the terminal. It is read
out of a Location the deployment chose, so percent-encoded ANSI or OSC survives
decodeURIComponent as real control bytes and could forge CLI output; control
characters are stripped and the name is bounded before it reaches the spinner.

resolveDeploymentUrl took the first source naming an app URL. A machine with
both a local checkout and a real deployment would be probed, printed, and
opened at whichever enumerated first, silently — so disagreeing sources are now
an error naming each candidate and asking for --url, the way
resolveFeatureSetupDestination already refuses ambiguity.

* fix(desktop,cli): fail closed on origin change, widen terminal sanitizer

The capability teardown could partially fail and still let the shell move.
Sequential awaits meant a filesystem-grant rejection skipped the browser-profile
clear entirely, and the new origin was already persisted by then, so the
incoming deployment inherited whatever survived — and startup restores it.

Now the two stores clear independently via allSettled and report which ones
survived, and the whole teardown runs BEFORE anything is written. A store that
cannot be emptied refuses the change outright and names what it could not
clear. Nothing is persisted at that point, so refusing leaves the shell exactly
where it was rather than half-applying. Validation moved up front for the same
reason: a typo now costs no teardown.

The terminal sanitizer matched only C0/DEL/C1 by range, so percent-encoded bidi
overrides and isolates survived decodeURIComponent and could still reorder what
the reader sees without emitting one control byte. Matched by Unicode class
instead — Cc covers the cursor controls, Cf covers the bidi ones.

Configuration discovery compared raw strings, so a trailing slash, a default
port, a host-case difference, or an ignored path read as two different servers
and demanded a --url override to settle an ambiguity that did not exist. Now
compared on the parsed origin, which is what the command ends up using.

* fix(cli): sanitize the installer name by Unicode group, not by escape list

U+2028 and U+2029 are Zl/Zp, so the Cc/Cf filter let them through and a
deployment-controlled redirect filename could still forge a status line.

Enumerating what to strip had cost a patch per class found — C0 and C1, then
the bidi overrides, now the line separators — so this keeps whole groups
instead. `C` removes every control, format, surrogate, private-use, and
unassigned code point, covering ESC and OSC, the bidi overrides and isolates,
zero-width characters, and the BOM; `Z` removes every space, line, and
paragraph separator. Separators become a plain space rather than vanishing so
a name is not run together at the seam, and runs are collapsed so the result
cannot be padded to push text off the line.

The regression table now names each class that reached the terminal in an
earlier round, so a future bypass says which one came back.

* fix(desktop): serialize server changes and report partial teardown honestly

Two problems in the same transaction.

The picker re-enabled Connect whenever the field changed, including while a
request was in flight, so typing and pressing Enter could start a second change
that interleaved its teardown and its write with the first — the later write,
not a single transition, deciding the next server. The transaction is now
serialized in the main process, the way the sign-out coordinator guards its
own teardown, since the IPC boundary is reachable regardless of what the page
does; the page keeps its button disabled for the whole request so it never asks
for something it will only be refused.

The stores clear independently, so one can succeed while the other fails. There
is nothing to roll back to — a revoked cookie jar and deleted security-scoped
bookmarks cannot be un-deleted — and moving anyway would hand the incoming
deployment whatever survived. So the change is still refused, but the message
no longer names only the failed store as though nothing else had happened: it
says some local access may already have been cleared, and that retrying
finishes the job. Clearing an already-empty store succeeds, so a retry is safe.
2026-08-26 17:43:11 -07:00
..
2026-07-28 19:25:59 -07:00

Sim Desktop (macOS)

A thin Electron shell around the hosted Sim web app. The renderer loads the configured origin (default https://www.sim.ai — the origin the server actually serves; the apex 301s there) as a normal top-level page in a bundled, pinned Chromium — rendering is identical to Chrome of that version on every machine. No UI is re-implemented and no server stack is bundled.

Layout

src/main/           # main process (bundled to dist/main.cjs)
  index.ts          # lifecycle + wiring
  ipc.ts            # the single channel table: gate, version floor, handler
  config.ts         # origin + settings store (userData/settings.json)
  app-routes.ts     # Sim routes the shell navigates to (menu + tray share them)
  atomic-json-file.ts # crash-safe write for the encrypted userData stores
  navigation.ts     # navigation classifier + openExternalSafe
  windows.ts        # window.open policy (full app windows, MCP popup, blank children)
  window.ts         # secure BrowserWindow, permissions, crash/hang recovery
  security-guards.ts# global web-contents guards, TLS policy
  csp.ts            # Content-Security-Policy fallback header
  handoff.ts        # 127.0.0.1 loopback login handoff + token redeem
  session-lifecycle.ts # sign-out teardown, 401 watcher, connect intercept
  load-health.ts    # offline/error page, auto-retry, watchdog
  local-filesystem.ts # session-scoped read-only directory grants + localfs:// broker
  local-filesystem-grant-store.ts # those grants, encrypted at rest
  desktop-settings.ts # renderer-facing settings surface
  downloads.ts      # will-download handling
  context-menu.ts   # native right-click + spellcheck
  telemetry-policy.ts # third-party analytics blocking
  observability.ts  # JSONL event log (userData/logs/desktop-events.log)
  updater.ts        # electron-updater wiring, channels, downgrade/block guards
  menu.ts           # role-based macOS menus
  tray.ts           # tray icon, recent-chat menu, environment marker
  browser-agent/    # the agent browser: tab lifecycle, panel geometry, CDP driver
  terminal/         # the agent terminal: PTY sessions, tmux, shell integration
  browser-credentials/ # saved passwords, OS-auth gated, safeStorage at rest
  browser-sites/    # imported site directory, safeStorage at rest
  browser-import/   # one-shot import of profiles, cookies and passwords
src/preload/        # contextBridge IPC bridge (bundled to dist/preload.cjs)
native/             # Node-API/AppKit bridge for native macOS Help docs search
static/             # bundled local pages (offline.html)
e2e/                # Playwright _electron smoke suite

Local development

bun install                 # workspace root
cd apps/desktop
bun run dev                 # bundle + launch against https://www.sim.ai
SIM_DESKTOP_ORIGIN=http://localhost:3000 bun run dev   # against local sim
  • bun run test — vitest unit suite (electron is mocked; runs anywhere).
  • bun run test:e2e — Playwright _electron smoke suite against a fixture origin (macOS, real Electron window).
  • bun run type-check / lint:check — standard workspace checks; CI picks these up automatically via turbo run.
  • SIM_DESKTOP_USER_DATA=<dir> isolates settings/partition state (used by e2e).

Everything is bundled by esbuild into dist/main.cjs + dist/preload.cjs — including electron-updater and the @sim/* packages — so the packaged app has no runtime node_modules and electron-builder needs no lockfile/npmRebuild step (this is the deliberate workaround for Bun ↔ electron-builder friction; there is no package-lock.json).

Auth model (read before touching auth)

  • The app loads the hosted origin top-level; better-auth session cookies live in a persistent partition (persist:sim, per-origin for self-hosts). Email/password and verified-lenient providers (GitHub) sign in fully in-window.
  • Google / Microsoft / SSO cannot OAuth inside an embedded browser (disallowed_useragent; UA spoofing is fingerprint-defeated — do not ship it). Navigation to those hosts from an auth surface is intercepted and rerouted through the system-browser handoff:
    1. App starts a one-shot 127.0.0.1 loopback listener on an ephemeral port and opens <origin>/desktop/auth?state=<random>&port=<port> in the browser. The state is single-use, in-memory (the app is always running when the callback returns, so nothing is persisted), and constant-time compared.
    2. apps/sim/app/desktop/auth/page.tsx requires a browser session (redirects through /login?callbackUrl=…) and renders a Continue gesture gate; only that click mints a one-time token (POST /api/desktop/auth/handoff) and sends the browser to the loopback (http://127.0.0.1:<port>/auth/callback?token=…&state=…, RFC 8252 §7.3). The gate is the security boundary — state and port are attacker-choosable in a crafted link, so a bare GET must never mint. The loopback is the single hand-back channel: no OS scheme registration, works identically in dev and packaged builds. Interception of loopback is mitigated the way PKCE mitigates it: the token is single-use, short-TTL, and bound to a 128-bit state the app compares in constant time. (RFC 8252's most-preferred callback is claimed-https / macOS universal links, which bind the OS to a verified app identity — a future hardening step that needs an associated-domains entitlement + apple-app-site-association on the origin.)
    3. The loopback fires the callback in the main process: the app validates the state, then a renderer in the app partition POSTs the token to /api/auth/one-time-token/verify (same-origin ⇒ trustedOrigins/CSRF pass; better-auth sets the session cookie and burns the token) and loads /workspace.
  • The app gets its own session, never the browser's. The token is minted by POST /api/desktop/auth/handoff (apps/sim/lib/auth/desktop-handoff.ts), which creates a new session row for the user and points the one-time token at that. Better-auth's own generateOneTimeToken binds to the calling session, so using it directly made the app and the authorizing browser share one row: signing out of either deleted the row the other was still presenting, and — because the session cookie cache is not revalidated against the database — the survivor kept looking signed in while every database-backed session resolution failed (the socket handshake logged Session not found and 401-looped). A session per device is what better-auth's own device authorization grant does and what RFC 8252 assumes: sign-out, revocation, and expiry apply to one surface at a time. Do not "simplify" this back to generateOneTimeToken.
  • Integration connects are same-window redirects (client.oauth2.link), not popups. Unknown provider hosts stay in-window (lenient default); Google/Microsoft connects get a native dialog offering to finish in the browser — the browser is signed in after the login handoff, tokens land server-side, the app just refreshes.
  • The MCP OAuth popup (mcp-oauth-*) is allowed as a same-partition child so window.opener.postMessage keeps working.
  • Sign-out revokes server-side first (POST /api/auth/sign-out from the app-origin renderer — a main-process session.fetch would be rejected by better-auth's origin check), then clears cookies/localStorage/IndexedDB/cache/service workers plus any pending handoff state. The revoke is not optional: since the app owns its own session row, clearing the partition alone would strand a live 30-day credential that nothing can revoke. Two signals trigger teardown: the /login?fromLogout=true navigation (fast path) and deletion of the better-auth session cookie confirmed by a get-session probe (robust backstop — catches every sign-out path, not just the settings one, and rotation can't cause a false teardown). API 401s (probe-confirmed) surface a native re-auth prompt.

Deviations from the original plan doc (deliberate):

  • One hand-back channel, not two. The plan proposed a sim:// deep link with a loopback fallback; that was collapsed to loopback-only. The app is always running when the callback returns (it started the loopback), so the custom scheme added complexity and a dev-only failure mode without buying anything — loopback works identically everywhere. No sim:// scheme is registered.
  • No launch-time session probe; the server's own redirect to /login covers the signed-out launch, and the last route is restored otherwise.
  • Browser-initiated /desktop/auth visits without a valid state+port render a friendly error and never mint a token.

Provider matrix (U5 spike — keep current)

The host list lives in src/main/navigation.ts (SYSTEM_BROWSER_IDP_HOSTS) and now applies to integration connects only — sign-in always goes through the system-browser handoff whatever the IdP, so no provider needs to be classified as embed-tolerant for login. (The old IN_WINDOW_IDP_HOSTS list existed to keep GitHub sign-in in-window; embedding a login is a one-way door in a chrome-less shell and splits better-auth's OAuth state across two cookie jars, so it was removed.) Verified so far: Google + Microsoft block embedding by policy. Before GA, run the spike for connects: a sample of integration connects (Notion, Slack, Linear, Atlassian, Box, Dropbox) plus SSO and Turnstile-on-signup in a packaged build, then update the list and this section.

Web-app coupling contract (audit on web-app changes)

A thin shell over a hosted web app unavoidably knows a few of the web app's conventions. They are listed here so a web-app change that would break the desktop app is auditable in one place. Each is a documented, deliberate coupling — not accidental. The robust long-term de-coupling for all of them is a two-way preload bridge (see "Desktop-only features" below): the web app signals intent (signalLogout(), markAuthSurface()) instead of the shell inferring it.

Shell code Depends on Breaks if the web app… Failure mode Mitigation today
session-lifecycle.ts isLogoutNavigation /login?fromLogout=true on sign-out renames the param/route fast-path teardown misses Cookie backstop (session-cookie deletion + probe) still tears down — no residue
session-lifecycle.ts isSessionCookieName better-auth cookie ends session_token changes the cookie name/prefix backstop misses (fast path still works for settings sign-out) better-auth library contract; stable. Revisit on better-auth major
navigation.ts AUTH_SURFACE_PREFIXES auth routes /login /signup /sso /reset-password /verify adds/renames an auth route SSO from the new route gets the connect dialog instead of login Update the list; unknown hosts from non-auth pages still default sensibly
navigation.ts IdP host lists provider OAuth hostnames + embedded-UA policy a provider changes hostnames/policy that provider's sign-in/connect misroutes until a new release Ships with the app; the U5 spike + upgrade checklist re-verify. Server-delivered config is the future fix
session-lifecycle.ts / handoff.ts /workspace default /workspace is the post-login home changes the default landing route post-login/last-route restore lands on a redirect/404 Web app's own routing usually redirects; low blast radius
navigation.ts mcp-oauth-* frame name hooks/queries/mcp.ts opens mcp-oauth-${id} renames the popup frame MCP popup treated as generic → opener lost, flow hangs String contract; add a shared constant if it churns
window.ts theme probe document.documentElement.classList.contains('dark') (next-themes attribute='class') drops the dark class convention pre-paint background may flash once Cosmetic only; self-corrects on next load
handoff.ts redeem POST /api/auth/one-time-token/verify sets the cookie better-auth changes the endpoint handoff sign-in fails better-auth built-in endpoint; pinned by the better-auth version
apps/sim/lib/auth/desktop-handoff.ts mint better-auth stores one-time tokens as verification rows keyed one-time-token:<token>, unhashed (storeToken: 'plain' default) better-auth renames the namespace or hashes by default every redeem fails with Invalid token Single constant in one module; the covering test asserts the identifier shape. Revisit on better-auth major

Overall this is within normal thin-wrapper coupling — every item is either backstopped (sign-out), cosmetic (theme), or a stable library/route contract. The only one that genuinely can't self-heal without a release is the IdP host list, which is inherent to the "pin Chromium, ship a binary" model and is managed by the upgrade program.

Packaging & release

Local unsigned build: bun run package:dir (app in release/mac-universal/). Signed: bun run package:mac with CSC_LINK/CSC_KEY_PASSWORD exported.

Pre-release share (no Developer ID yet): SIM_DESKTOP_DEFAULT_ORIGIN=https://www.dev.sim.ai bun run package:share builds a DMG whose fresh installs default to that origin (baked at build time; official builds leave it unset → prod) and skips per-file signature timestamps. Recipients must clear quarantine once: xattr -cr /Applications/Sim.app.

The build also derives the app icon from SIM_DESKTOP_DEFAULT_ORIGIN. Every channel uses the exact production icon with its white background and black sim mark. Non-production channels add a thin outline using existing platform colors: dev uses orange, staging uses Loop blue, and localhost uses Workflow violet. The macOS menu-bar icon also carries a compact D, S, or L subscript for those environments; production remains unmarked. Native Icon Composer assets live in build/; scripts/build.ts copies the selected variant to the ignored build/generated-icon.icon path consumed by electron-builder. Electron-builder compiles it to Assets.car and derives the legacy .icns fallback from the same source. Matching 512px PNGs in static/ provide the Dock icon for unpackaged runs.

CI (.github/workflows/desktop-release.yml, wired into ci.yml):

  • Stable builds run only after create-release on a vX.Y.Z: commit to main — never before: scripts/create-single-release.ts skips creation if the tag exists, so a desktop job publishing first would eat the changelog. Stable assets remain on simstudioai/sim; dev/staging assets publish to the public simstudioai/sim-desktop-releases repository so source-repository followers are not notified for internal shell builds. The job builds --publish never and uploads assets with gh release upload --clobber (idempotent re-runs).
  • Secrets gate: check-desktop-signing in ci.yml probes the six Apple secrets and skips the desktop job with a warning until they exist — releases never fail on a missing Apple account, and the first release after the secrets land ships desktop artifacts automatically. Manual/one-off builds: Actions → "Desktop Release (macOS)" → Run workflow with a vX.Y.Z version (publish: false uploads artifacts to the run instead of the release).
  • The product semver is injected from the release tag into apps/desktop/package.json at build time (repo package versions are placeholders). A mismatch guard fails the build.
  • Fuses are flipped at package time (electronFuses in electron-builder.yml): runAsNode off, NODE_OPTIONS off, inspect args off, ASAR-only + integrity validation, cookie encryption on, strictlyRequireAllFuses so new fuses fail loudly on Electron bumps.
  • Cookie-encryption go/no-go: on every Electron bump, verify a packaged build keeps its session across relaunch (there are historical cookie-persistence bugs with the EnableCookieEncryption fuse). If it reproduces, set enableCookieEncryption: false and record it here.

Required repo secrets (owner: whoever holds the Apple Developer account; calendar the expiries — an expired cert/API key breaks every release):

Secret Contents
CSC_LINK base64 of the Developer ID Application .p12
CSC_KEY_PASSWORD .p12 password
APPLE_API_KEY_P8 App Store Connect API key file contents (.p8)
APPLE_API_KEY_ID API key ID
APPLE_API_ISSUER API issuer ID
APPLE_TEAM_ID Developer team ID
DESKTOP_RELEASE_TOKEN Fine-grained GitHub token with Contents: write on only simstudioai/sim-desktop-releases; used to create, upload, publish, and prune dev/staging releases

Desktop-only features (how to add them cleanly)

Yes — the architecture has a single, clean seam for native features, and nothing about "the renderer is the hosted web app" gets in the way. The rules:

  1. One bridge. The preload (src/preload/index.ts) exposes window.simDesktop via contextBridge on the main window. This is the only channel between web content and native capability. It exposes narrow, typed methods — never raw ipcRenderer (Electron security checklist item 20).
  2. Feature-detect, never assume. The same web app is served to browsers and to the desktop from one origin, so a desktop feature is progressive enhancement: if (window.simDesktop) { … }. In a browser window.simDesktop is undefined and the feature is simply absent. (isHosted already tags these sessions for analytics.)
  3. Gate in main. Every channel is validated in src/main/ipc.ts by sender frame — app-origin for capability calls, bundled file: pages for shell-control calls (checklist item 17). A new native feature adds one gated channel there.
  4. Single-source the contract. apps/sim cannot import from apps/desktop (monorepo rule: apps/* → packages/* only). The bridge interface lives in the shared types-only packages/desktop-bridge package, which both the preload and web app consume.

Concrete example — a "Reveal in Finder" button:

// packages/desktop-bridge/index.ts  (shared contract)
export interface SimDesktopApi { showItemInFolder(path: string): void /* …existing methods… */ }

// apps/desktop/src/preload/index.ts   (implement)
showItemInFolder: (path: string) => ipcRenderer.send('desktop:show-item', path),

// apps/desktop/src/main/ipc.ts        (gate)
ipcMain.on('desktop:show-item', (event, path) => {
  if (!isAppOriginSender(event, deps.appOrigin()) || typeof path !== 'string') return
  shell.showItemInFolder(path)
})

// apps/sim  (consume — progressive enhancement)
const desktop = useDesktop()
{desktop && <Button onClick={() => desktop.showItemInFolder(file.path)}>Reveal in Finder</Button>}

Good fits for the bridge: OS notifications + dock badge on workflow completion, global shortcuts, "reveal in Finder", tray, secure OS-keychain storage. Anything that touches the server/DB still goes through normal APIs — the bridge is only for native capability. This same bridge is also the robust way to retire the web-app couplings in the table above: have the web app tell the shell (signalLogout(), markAuthSurface()) instead of the shell inferring from URLs.

Local filesystem access

Copilot can inspect user-selected local directories through the ordinary VFS tools. Granted folders appear beneath the top-level user-local/ namespace, and glob, grep, and read are routed to Electron only when their path/pattern is explicitly scoped there. This capability is:

  • Explicit and read-only: only a user click may open the native folder picker or revoke a grant; model tool calls cannot do either. There are no write/delete/execute/upload operations.
  • Remembered securely: grants are encrypted in Electron's private app data with OS-backed safeStorage and restored with the same opaque URI after a normal app restart. (A security-scoped bookmark is stored alongside each grant, but it is a no-op in the current Developer ID build — only the macOS App Sandbox consumes it — and is kept purely for forward-compatibility should a sandboxed/MAS build ever ship.) There is no plaintext fallback: when secure storage is unavailable, the returned mount has remembered: false and lasts only for that app session.
  • Revocable: Desktop settings removes one grant. All grants are removed on explicit sign-out or server-origin change so another Sim account or server cannot inherit them. Normal app quit only releases active OS handles and keeps the encrypted grants.
  • Opaque: the model sees canonical paths such as user-local/Project--<mount-id>/README.md, never host paths or internal localfs:// URIs. Electron resolves every request, checks lexical and realpath containment, and refuses symlink escapes.
  • Desktop-only: the web app advertises desktopCapabilities.localFilesystem only when the Electron bridge is present. Mothership adds the user-local/ prompt surface and per-call client routing only for that capability, including delegated and resumed work.
  • Bound to a live Copilot call: before a native read/search or browser action, Electron asks the authenticated Sim origin for the pending tool-call record. Local requests must exactly match its persisted operation, path, and options; browser actions run with the persisted arguments rather than renderer-supplied ones. Completed, failed, and aborted runs are rejected.
  • Abort-aware and bounded: stop/cancel propagates to active native scans and reads. File size, aggregate grep bytes, line, result, traversal-depth, and scan-count limits remain enforced in Electron, and unsafe regular expressions are rejected before execution.

Raw local file bytes are never exposed through the preload bridge and cannot be staged or uploaded by a model. Bounded text read/search results are returned to the active Copilot request; a user must use the normal attachment UI when they want the file itself to leave the device.

Auto-update, channels, rollout, rollback

  • electron-updater reads the deployment's /api/desktop/update feed; production resolves stable releases from simstudioai/sim, while dev/staging resolve prereleases from simstudioai/sim-desktop-releases. Artifact downloads go directly to GitHub and deltas use .zip.blockmap. Install is prompt-based (Restart Now / Later; Later installs on quit) — never forced mid-session.
  • Streams: production follows stable X.Y.Z releases, dev follows -dev.N, and staging follows -staging.N. The feed still recognizes legacy -alpha.N/-beta.N releases during migration.
  • Staged rollout: after publishing, edit stagingPercentage: 10 into the release's latest-mac.yml, then raise as crash metrics stay clean.
  • Rollback: a pulled release must be superseded by a higher version — users on the broken build will not reinstall an equal one. (A blocked-versions kill-switch was removed as unwired dead code; reintroduce it in updater.ts if a remote config source ever exists to feed it.)
  • Ship the DMG and tell users to install to /Applications — App Translocation breaks Squirrel.Mac updates from quarantined paths.

Self-hosting

  • Point Settings… (Cmd+,) at your instance. HTTPS required (HTTP for localhost only); each origin gets an isolated cookie partition.
  • Deploy the /desktop/auth page (ships with apps/sim) and include your desktop users' origin in TRUSTED_ORIGINS if it differs from NEXT_PUBLIC_APP_URL.
  • TLS must be system-trusted — the shell hard-rejects certificate errors (no in-app bypass). Install private CA roots in the macOS keychain.
  • DISABLE_AUTH instances: the web app serves an anonymous session; the shell needs no special handling, but understand that anyone with the app and your origin has full access.
  • Forks: repoint publish.owner/repo in electron-builder.yml or strip the updater.

Known caveats

  • Microphone and camera are denied by design (the permission matrix grants only sanitized clipboard writes to the app origin).
  • Default Electron ships H.264/AAC/MP3 — do not swap in the codec-free ffmpeg build.
  • Third-party web analytics (GTM/GA) are blocked at the network layer by default (blockThirdPartyAnalytics); first-party PostHog /ingest is untouched.
  • Cmd+F find-in-page overlay is not implemented (Monaco and tables ship their own finds); revisit if users ask.
  • Sign-in uses only the 127.0.0.1 loopback callback, which needs no OS registration — so it completes identically under bun run dev (unpackaged) and in a packaged build. There is no custom URL scheme.

Electron upgrades

Cadence: Electron ships a major every ~8 weeks and supports the latest 3 — budget a bump every ~46 months and adopt security patches within ~2 weeks. Follow docs/electron-upgrade-checklist.md; the desktop-e2e.yml canary leg (electron@latest) is the early-warning signal.