Repository navigation
measure and speed up rstudio desktop startup - #18716
Merged
Merged
Conversation
When RSTUDIO_STARTUP_TIMING names a file, the Electron main process, the rsession process, and the GWT client each append their startup checkpoints to it as JSON lines, so one timeline can be reconstructed across all three: - desktop (src/node/desktop/src/main/startup-timing.ts): process start, app ready, R detection, session spawn, window creation, page load, and workbench initialization; it also copies the renderer's navigation, resource, and performance.mark() entries into the file once the workbench is up - rsession (src/cpp/core/StartupTiming.cpp): main, options, prefs, the http listener, R initialization, module initialization (with a span per sourced module R file), client_init, and deferred init - client (org.rstudio.core.client.StartupTiming): performance marks from module load through the first painted workbench frame `npm run startup-timing` (tasks/startup-timing.ts) launches RStudio Desktop repeatedly with the variable set and prints the merged timeline as medians across runs, followed by the longest measured spans.
…once the session listens Three changes to the desktop's launch sequence, each measured with the startup timing checkpoints: - R was queried twice for the same executable (once while scanning for installations, once to prepare the environment), and libR's architecture was checked by spawning /usr/bin/file. Detection results are now cached per executable and the Mach-O header is read directly. - On macOS, rsession asked the user's login shell for PATH at the start of every launch (SessionPath.cpp), which with a typical profile costs hundreds of milliseconds on the critical path. The desktop now asks the shell itself, at the top of main.ts, and passes the answer to rsession with RSTUDIO_SESSION_PATH_INITIALIZED=1, which makes the session skip its own query. If the shell has not answered by the time the session is launched, the previous launch's answer (kept in the desktop's state store) is used and the fresh one is remembered for next time; only a first launch with nothing remembered waits. - The main window navigated to the session URL immediately, which failed because the session was not yet listening, and then showed the loading page and polled at 200 ms intervals before reloading. It now shows the loading page first and navigates as soon as a 20 ms probe finds the listener up.
In desktop and standalone modes the GWT file handler was registered at the end of rInit, after R and every module initializer had run, and requests were only drained from the connection queue by the main thread once it reached its first waitForMethod. The client could therefore not begin loading until the session was fully initialized. The file handler is now registered before the http listener starts, and the listener thread serves GET requests that fall through to it (no module-registered handler, not an rpc or events request) directly, the same way it already handles offlineable requests. The page and its scripts load while R initializes, and the first request the main thread sees is client_init. Files served in desktop mode are no longer gzipped: over a loopback connection compressing the multi-megabyte client costs far more than sending it uncompressed. Server mode keeps compression.
Detecting R means running it, which costs about 150 ms, and startup did it only once it needed the answer. The query now starts at the top of main.ts and fills the same per-executable cache the synchronous path reads, so by the time the launch sequence detects R the answer is already there; run() awaits the background query first, which on a first launch is where any remaining wait is paid. The background query tries the executables startup would pick anyway -- RSTUDIO_WHICH_R, then the platform's stored, registry, or well-known locations -- and stops at the first one that answers. Choosing the R candidates and parsing the query output are now shared with the synchronous path rather than duplicated, and the query result parser is exported so it can be tested without launching R. R detection no longer appears on the critical path at all: it resolves about 1 ms after the launch sequence asks for it, and the session is spawned roughly 135 ms earlier.
Distinguishes 'the probe has not started yet' from 'the probe is waiting', which is what separates main-window construction from work blocking the main thread while the probe is in flight.
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 00:44 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 00:44 — with
GitHub Actions
Inactive
installCode=false makes the xsiframe linker add a script tag (we always serve same-origin), so the browser parses the 6.8 MB permutation on a background thread instead of the renderer main thread (~125 ms there), and the compiled-code cache can apply across launches once the origin is stable. Wall-clock neutral on its own; groundwork for overlapping startup work with the parse.
the boot sequence serialized ace + style injection ahead of the client_init request, though neither is needed to send it; the main window now starts the application first and loads ace while the round trip is in flight, joining on ace (via a second AceEditor.load, a no-op once loaded) before building the workbench. satellites still load ace up front since they construct editors immediately. moves client_init ~40 ms earlier after module load.
…ound trips the local pref refresh both the workbench and the automation agent need is the synchronous first step of writeState()/writeUserPrefs(); the rpc round trips only echo those values back to the server, and were queued behind the session's deferred init (~115 ms on the startup critical path). fire them without waiting.
the catch around response dispatch was meant for json parsing, but also caught exceptions thrown by response handlers, converting real client bugs into bogus 'transmission error' retries and hiding them from the uncaught-exception log. only the parse is caught now.
with workbench startup no longer blocked on the pref write round trips, a font-size change can request pane metrics before the console pane has created its widget; report 0, the documented 'no valid measurement yet' value.
the base ace load (AceEditor.load) no longer includes the vim and emacs keybinding bundles, and loads acesupport and ext-language-tools in parallel after ace itself. the keybindings load on demand, requested by the first editor whose keybinding pref needs them (AceEditor.loadKeybindings); setup that must piggyback on that load -- the vim ex commands, the emacs Return unbinding, the incremental-search message hook -- runs via onKeybindingsLoaded or is re-applied in the load completion, and code that touched the modules unconditionally (copy/paste unmap/remap, VimAPI resolution, the TextEditingTarget and AceEditorNative static initializers) now tolerates their absence. saves two fetches (~140 KB) and their evaluation on every startup for users on default keybindings, and trims satellite window boot, where ace still loads up front.
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 02:03 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 02:03 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 02:03 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 02:03 — with
GitHub Actions
Inactive
wraps the callback-counter pattern from AceEditor.load into a reusable class: each add() call contributes a stage, stages load sequentially, and the scripts within a stage load in parallel; onFinished handlers run after every successful execution. AceEditor's base and keybindings loads now declare their stages with it, which also parallelizes the vim/emacs fetch.
- treat a signal-killed rsession as exited in the session listener probe loop (exitCode stays null on signals) - parse the login shell's PATH on 'close' rather than 'exit', so stdout is fully drained before the answer is cached - don't block the explicitly requested Windows R chooser on the background R probe (the user may be choosing a different R precisely because the default one hangs) - restore the default eval-based install in the Super Dev Mode modules: the code server serves from another origin, which the script-tag install requires to be same-origin - report a null RpcResponse parse result as a transmission error; parse failures return null rather than throw, so they previously relied on the response handler crashing inside the old catch - serve listener-thread static assets via the default handler directly and gate the fast path on an atomic 'registered' flag, so a module handler registered between the check and the dispatch can't run on the listener thread
- harvest the renderer timeline once the client's deferred-init-completed mark exists (bounded poll) instead of a fixed 3 s delay, so slow launches are captured in full before the measurement run ends - keep the loading UI up until the workbench is about to be built, so a client_init response that beats the ace load doesn't expose a blank shell (switch-project keeps its existing 10 s overlay timer) - record the session-url-reachable checkpoint only when the probe actually succeeded, not from .finally()
- thread the compress flag through setCacheableFile / setIndefiniteCacheableFile, so the desktop's no-gzip-over-loopback behavior also covers cacheable assets (including the multi-megabyte permutation), not just the main page - replace the wall-clock detect-r cache test with a deterministic one: a stand-in R script answers the query, is deleted, and the synchronous path must still succeed, which is only possible via the cache
The startup writeState()/writeUserPrefs() calls existed only for their synchronous updatePrefs() first step: UserPrefs can be GIN-constructed before the client_init response arrives (eager singletons like Assistant and both application headers inject it during Application construction), so its pref layers start out empty. The old comment's claim that this is desktop-exclusive is stale, and the server round trips just echoed sessionInfo's own values back, unconditionally rewriting the pref and state files on every IDE load. Add UserPrefs/UserState.loadFromSessionInfo() and call that instead, saving two RPCs and two file writes per startup.
- bound each session listener probe with a request timeout, so a connected socket that never answers (e.g. another process shadowing the port) cannot hang startup past the loop's 30 s ceiling - drive the detect-r cache test through startRDetection() and rDetectionReady(), the wiring startup actually uses
registerPrefs() enumerates userPrefs_.allPrefs(); if UserPrefs was constructed before client_init and never refreshed from the session info, every pref registers with its default value (the #17733 failure mode, which surfaced as an anonymous gray screen). Check explicitly and throw with a clear message instead -- a plain Java assert would be compiled out of the optimized GWT output that automation runs against. Verified both ways: with the startup loadFromSessionInfo() calls temporarily disabled, agent startup fails with the new exception attributed to initializeAgent in the rsession log; with them in place, the vimrc keybindings desktop e2e suite passes.
the gwt compile now writes a gzipped sibling next to each large *.cache.js / *.cache.css output (tools/precompress.js, run from the gwtc target with the pinned node), and the file handler serves the sibling with Content-Encoding: gzip when the client accepts it. the compression cost moves from every request to once per build: server mode stops re-deflating the same immutable assets on every first load, and the desktop gets compact transfers at zero runtime cost. the compress option continues to govern only runtime deflate.
- skip the R-probe wait whenever the Windows chooser is going to show (explicitly requested, or a first run with no remembered selection), not just when explicitly requested - make the login-shell PATH timeout terminal: resolve null immediately and SIGKILL the shell, so a profile that traps the signal cannot leave a first launch waiting
- when the desktop's bounded login-shell query fails or times out, tell
the session to keep the inherited PATH (its own probe has no timeout
and would hang on the same profile)
- ignore stored Windows R candidates that no longer exist on disk when
predicting whether the chooser will show
- write timing-harvest-timeout instead of timing-harvested when the
client never completes deferred init, and have the measurement task
fail that run as incomplete
- treat the synthesized placeholder pref layer ([{}], no values) as not
loaded in hasLoadedLayers(), so the agent-init tripwire catches the
missing-user-layer case too
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:35 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 3, 2026 16:41 — with
GitHub Actions
Inactive
- keep a terminal launch's PATH on macOS: when the inherited PATH already contains /usr/local/bin (the session's own initializePath() heuristic), the desktop no longer overrides it with the login shell's answer, so customizations like an activated conda environment survive; such launches also skip the first-launch wait for the shell query - a libR.dylib read failure now fails the launch again instead of silently letting the two callers guess different architectures - install the Ace keyboard previewer and event listeners even while the vim/emacs keybinding bundles are still loading; only the choice of keyboard handler waits on them - escape checkpoint names when writing startup-timing JSON lines (one call site embeds a request URI) - the startup-timing report skips runs whose timing file has no checkpoints instead of crashing on them - reword the stale s_gwtHandlersRegistered comment (the handlers were never registered in server mode) and drop the now-dead duplicate node.bin block in build.xml
the listener thread now hands static asset requests to their own queue, drained by a worker thread (desktop and standalone modes only), so their file reads and socket writes can no longer stall connection accepts or abort/suspend/interrupt handling on the listener thread
Collaborator
Author
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:44 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:44 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:46 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:46 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:55 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:58 — with
GitHub Actions
Inactive
kevinushey
temporarily deployed
to
e2e-playwright
September 4, 2026 00:58 — with
GitHub Actions
Inactive
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Make RStudio Desktop start faster, and make it possible to see where startup time goes so future changes can be measured rather than guessed at.
Measured as a matched pair on this machine (Apple silicon, dev build, fresh config and data home per run; the baseline is the timing-instrumentation commit alone, built in its own worktree, with both series run back-to-back under the same ambient load): with the full branch the workbench paints at a median of 1,927 ms after Electron process creation versus 3,627 ms for the baseline (47% faster), and a first launch after install goes from 5.6 s to 2.6 s (53% faster). Absolute numbers track machine load -- an earlier pair measured on a quieter machine mid-branch came out 2,511 ms -> 1,279 ms with the same ratio.
Approach
Two waves of commits, intended to be reviewed separately. The first four groups instrument startup and fix the desktop/session sides; a second wave (commits from
install the initial gwt fragment...on) addresses the client side, guided by Chromium startup traces of the renderer.1. Startup timing checkpoints. With
RSTUDIO_STARTUP_TIMING=<file>set, the Electron main process,rsession, and the GWT client each append JSON-line checkpoints to that file, giving one timeline across all three processes.npm run startup-timing -- --runs=N(a new task intasks/) launches the app repeatedly and prints the merged timeline as medians plus the longest spans;--app=<binary>measures an installed build,--report=<dir>re-prints. The client's checkpoints areperformance.mark("rstudio:...")entries, so they also show up in the DevTools Performance panel. Zero cost when the variable is unset.2. Desktop launch sequence (
src/node/desktop):/usr/bin/filecalls; detection results are cached per executable and the Mach-O header is read directly.main.tsand passes the answer to rsession withRSTUDIO_SESSION_PATH_INITIALIZED=1, so the session skips its own query. If the shell has not answered by launch time, the previous launch's answer (kept in the desktop's state store) is used and the fresh one is remembered for next time; only a first launch with nothing remembered waits. Machines with a fast profile therefore always get a fresh PATH; on slow profiles a changed profile applies from the following launch.3. Query R while Electron is still starting (
src/node/desktop). Detecting R means running it (~150 ms), and startup did that only once it needed the answer. The query now starts at the top ofmain.tsand fills the same cache the synchronous path reads, trying the executables startup would pick anyway and stopping at the first that answers. Choosing candidates and parsing the query output are now shared with the synchronous path instead of duplicated. R detection no longer appears on the critical path: it resolves about 1 ms after the launch sequence asks, and the session spawns roughly 135 ms earlier.4. Session serves the client during R init (
src/cpp):client_init. Measured alone this saved ~440 ms.*.cache.js/*.cache.css) are now gzipped once at build time (tools/precompress.js, run from thegwtcant target), and the file handler serves the.gzsibling withContent-Encoding: gzipwhenever the client accepts it -- in both desktop and server modes, since a precompressed file costs nothing to serve and reads less disk. Server mode stops re-deflating the same immutable assets on every first load.Baseline budget and the ranked remaining opportunities (desktop main-thread work delaying the probe by ~200 ms, the serialized
set_user_state/set_user_prefsround trips beforeinitializeWorkbench, a stable per-user port so Chromium's caches survive launches, lazy quarto/git init) are written up in the profiling report; happy to file follow-ups.5. Client-side wave (
src/gwt), from renderer trace analysis:installCode=falsemakes the linker use a script tag instead: the parse moves to a background thread and the code becomes cache-eligible (the cache also needs a stable origin across launches, a possible follow-up). Wall-clock neutral alone; groundwork for the rest.client_init, though neither is needed to send it; the main window now sendsclient_initfirst and loads Ace during the round trip, joining on Ace before building the workbench (~40 ms).initializeWorkbenchno longer waits for theset_user_state/set_user_prefsround trips (~115 ms, queued behind the session's deferred init); the local pref refresh they perform synchronously is all the workbench needs.AsyncJavaScriptLoaderexpresses staged parallel loads). Setup that must piggyback on the keybindings' arrival (vim ex commands, the emacs Return unbinding, the incremental-search message hook) re-runs on load, and everything that touched those modules unconditionally now tolerates their absence.RpcRequestcaught exceptions thrown by response handlers (not just JSON parsing) and misreported them as transmission errors, hiding real client bugs behind bogus retries -- the catch now covers only the parse; andConsolePane.getCharacterWidth()could be called before the console shell exists once workbench init stopped blocking on the pref writes (it now reports 0, the documented "no valid measurement" value).Open points for review:
SessionHttpConnectionListenerImpl, which all platforms use: Windows has constructed aTcpIpHttpConnectionListener(derived from it) since a7ffd1f (2017), so it gets the fast path too.SessionNamedPipeHttpConnectionListener.hppduplicates the enqueue logic without the fast path, but nothing has included it since that commit; it could be deleted in a separate cleanup.zsh -l -cdoes not read~/.zshrc; that is pre-existing behavior ofSessionPath.cpp, not changed here.Automated Tests
npm test,npm run lint, andnpm run typecheckpass insrc/node/desktop.tests/panes/editorPlaywright suite passes against the client-side wave (179 passed; the 13 failures are all@aiCopilot tests that need credentials not available locally), including the vimrc keybinding tests, which exercise the lazy vim path end-to-end.PW_RUN_SMOKE=1 npm run test:desktop-dev -- tests/smoke/startup.test.ts) passes against the dev build, so the automation-agent launch path (no splash, pre-seeded cookies) still comes up.QA Notes
Sys.getenv("PATH")with a new Terminal window; they should match on the second launch and after (the first launch after install still asks the shell before starting the session).npm run startup-timing -- --runs=3from the checkout to reproduce the timeline. Run 1 is a first launch; compare runs 2 and later.RSTUDIO_SESSION_SLEEP_ON_STARTUP=10): the loading page should appear immediately and the IDE should load when the session comes up, with no error page.