diff --git a/content/blog/shiny-r-1-15/_feature-src/capture.py b/content/blog/shiny-r-1-15/_feature-src/capture.py new file mode 100644 index 000000000..c0a3b7e1a --- /dev/null +++ b/content/blog/shiny-r-1-15/_feature-src/capture.py @@ -0,0 +1,37 @@ +"""Regenerate the post's feature image from feature.html. + +Writes feature.png (1920x1080) to the post directory (the parent of this +folder). + +Usage: + + uv run --with playwright python capture.py +""" + +import pathlib + +from playwright.sync_api import sync_playwright + +HERE = pathlib.Path(__file__).parent +POST_DIR = HERE.parent +SRC = (HERE / "feature.html").as_uri() + +WIDTH, HEIGHT = 1200, 675 # 16:9; 1.6x device scale gives 1920x1080 + +with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page( + viewport={"width": WIDTH, "height": HEIGHT}, + device_scale_factor=1.6, + ) + page.goto(SRC) + # Fail loudly if the site fonts did not load; a system fallback looks wrong. + page.evaluate("() => document.fonts.ready") + for spec in ('600 16px "Open Sans"', '500 16px "Source Code Pro"'): + if not page.evaluate(f"() => document.fonts.check('{spec}')"): + raise SystemExit(f"font not loaded: {spec}") + page.wait_for_timeout(300) + page.screenshot(path=str(POST_DIR / "feature.png")) + browser.close() + +print("feature.png written (1920x1080)") diff --git a/content/blog/shiny-r-1-15/_feature-src/feature.html b/content/blog/shiny-r-1-15/_feature-src/feature.html new file mode 100644 index 000000000..a83bc2195 --- /dev/null +++ b/content/blog/shiny-r-1-15/_feature-src/feature.html @@ -0,0 +1,158 @@ + + + + + + + + +
+
New release
+

Shiny for R 1.15

+
A bundled agent skill for your coding agent, and autoreload out of the box
+
+ +
+ Agent Skill +
+
+
+
SKILL.md
+
--- +name: shiny-for-r +--- +# Shiny for R
+
An index that sends your coding agent to the right reference
+
+
+ reactivitymodules + asyncextended-tasks + layoutsnavigation + dashboard-designdynamic-ui + plotstablesfiles + bookmarkingtheming-assets + testingdebugging + opentelemetry21 references +
+
+
+
+ +
+ shiny.autoreload = TRUE +
+
Save app.R→app reloads
+
+
+
✓Reloaded on save
+
+
watcher is now built in. No polling.
+
+
+ +
+ btw +
+
+
> btw::btw_skill_install_package("shiny")
+
+
copies the skill to
+
+ + .btw/skills/shiny-for-r/ +
+
Or attach shiny and let btw find it.
+
+
+ + diff --git a/content/blog/shiny-r-1-15/_gif-src/autoreload-app/app.R b/content/blog/shiny-r-1-15/_gif-src/autoreload-app/app.R new file mode 100644 index 000000000..7d606d1f4 --- /dev/null +++ b/content/blog/shiny-r-1-15/_gif-src/autoreload-app/app.R @@ -0,0 +1,15 @@ +library(shiny) +library(bslib) + +ui <- page_fillable( + h2("Old Faithful"), + card(plotOutput("plot")) +) + +server <- function(input, output, session) { + output$plot <- renderPlot({ + hist(faithful$waiting, col = "steelblue", border = "white") + }) +} + +shinyApp(ui, server) diff --git a/content/blog/shiny-r-1-15/_gif-src/capture.py b/content/blog/shiny-r-1-15/_gif-src/capture.py new file mode 100644 index 000000000..7642d0369 --- /dev/null +++ b/content/blog/shiny-r-1-15/_gif-src/capture.py @@ -0,0 +1,141 @@ +"""Regenerate autoreload.gif: a real recording of Shiny's autoreload. + +Runs a copy of autoreload-app/ with `options(shiny.autoreload = TRUE)`, shows +its source next to the live app (stage.html), then edits and saves the file +twice. Each save is a real write to disk, and the browser pane is the real app +reloading. Only the editor pane is drawn by the stage. + +Usage (requires R with shiny, bslib and watcher): + + uv run --with playwright --with pillow python capture.py +""" + +import io +import json +import pathlib +import shutil +import socket +import subprocess +import tempfile +import time +import urllib.request + +from PIL import Image +from playwright.sync_api import sync_playwright + +HERE = pathlib.Path(__file__).parent +POST_DIR = HERE.parent +SOURCE = (HERE / "autoreload-app" / "app.R").read_text() + +# (text to find, replacement, text the reloaded app must show or None) +EDITS = [ + ('col = "steelblue"', 'col = "tomato"', None), + ('h2("Old Faithful")', 'h2("Old Faithful: time between eruptions")', "time between eruptions"), +] + +frames: list[tuple[Image.Image, int]] = [] + + +def snap(page, ms: int) -> None: + img = Image.open(io.BytesIO(page.screenshot())).convert("RGB") + frames.append((img, ms)) + + +def show(page, text: str, changed: list[int], state: str) -> None: + page.evaluate( + f"showCode({json.dumps(text)}, {json.dumps(changed)}, {json.dumps(state)})" + ) + + +def plot_src(app) -> str: + app.locator("#plot img").wait_for() + return app.locator("#plot img").get_attribute("src") + + +with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + +app_dir = pathlib.Path(tempfile.mkdtemp()) / "app" +shutil.copytree(HERE / "autoreload-app", app_dir) +proc = subprocess.Popen( + [ + "Rscript", + "-e", + f"options(shiny.autoreload = TRUE); shiny::runApp('{app_dir}', port = {port})", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, +) +try: + url = f"http://127.0.0.1:{port}/" + for _ in range(60): + try: + urllib.request.urlopen(url, timeout=1) + break + except OSError: + time.sleep(0.5) + else: + raise SystemExit("app did not start") + + with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page(viewport={"width": 1100, "height": 480}) + page.goto((HERE / "stage.html").as_uri()) + page.evaluate("() => document.fonts.ready") + page.evaluate(f"document.getElementById('app').src = {json.dumps(url)}") + app = page.frame_locator("#app") + text = SOURCE + show(page, text, [], "saved") + before = plot_src(app) + page.wait_for_timeout(500) + snap(page, 1800) + + for old, new, expect in EDITS: + line = next(i for i, l in enumerate(text.split("\n")) if old in l) + text = text.replace(old, new) + show(page, text, [line], "unsaved") + snap(page, 1200) + + (app_dir / "app.R").write_text(text) # the real save + show(page, text, [line], "saved") + snap(page, 500) + # Wait for the real reload: the page text or the plot image changes. + deadline = time.time() + 20 + while time.time() < deadline: + page.wait_for_timeout(150) + try: + if expect: + done = app.get_by_text(expect).count() > 0 + else: + done = plot_src(app) != before + if done: + break + except Exception: + pass # the iframe is mid-reload + else: + raise SystemExit(f"app did not reload after editing: {old}") + before = plot_src(app) + page.wait_for_timeout(600) + snap(page, 2200) + browser.close() +finally: + proc.terminate() + proc.wait() + shutil.rmtree(app_dir.parent) + +# One shared palette keeps the GIF small and stops colours shifting per frame. +both = Image.new("RGB", (frames[0][0].width, frames[0][0].height * 2)) +both.paste(frames[0][0], (0, 0)) +both.paste(frames[-1][0], (0, frames[0][0].height)) +palette = both.quantize(colors=128, dither=Image.Dither.NONE) +images = [f.quantize(palette=palette, dither=Image.Dither.NONE) for f, _ in frames] +images[0].save( + POST_DIR / "autoreload.gif", + save_all=True, + append_images=images[1:], + duration=[ms for _, ms in frames], + loop=0, + optimize=True, +) +print(f"autoreload.gif written ({len(frames)} frames)") diff --git a/content/blog/shiny-r-1-15/_gif-src/stage.html b/content/blog/shiny-r-1-15/_gif-src/stage.html new file mode 100644 index 000000000..2e9dc4cd9 --- /dev/null +++ b/content/blog/shiny-r-1-15/_gif-src/stage.html @@ -0,0 +1,59 @@ + + + + + + + + +
+
app.RSaved
+

+  
+
+
Browser
+
+
+ + + diff --git a/content/blog/shiny-r-1-15/_screenshot-src/after-app/app.R b/content/blog/shiny-r-1-15/_screenshot-src/after-app/app.R new file mode 100644 index 000000000..913df61fb --- /dev/null +++ b/content/blog/shiny-r-1-15/_screenshot-src/after-app/app.R @@ -0,0 +1,41 @@ +# The same app as ../before-app, written the way the shiny-for-r skill points +# agents: a bslib page with a sidebar, value boxes, and real navigation. +library(shiny) +library(bslib) +library(ggplot2) + +ui <- page_sidebar( + title = "Fuel economy", + sidebar = sidebar( + checkboxGroupInput("cyl", "Cylinders", c(4, 6, 8), selected = c(4, 6, 8)), + sliderInput("hp", "Horsepower", 50, 340, c(50, 340)) + ), + layout_columns( + fill = FALSE, + value_box("Cars", textOutput("n")), + value_box("Average mpg", textOutput("mpg")), + value_box("Average weight", textOutput("wt")) + ), + navset_card_underline( + nav_panel("Plot", plotOutput("plot")), + nav_panel("Data", tableOutput("data")) + ) +) + +server <- function(input, output, session) { + cars <- reactive({ + mtcars[mtcars$cyl %in% input$cyl & mtcars$hp >= input$hp[1] & mtcars$hp <= input$hp[2], ] + }) + output$n <- renderText(nrow(cars())) + output$mpg <- renderText(round(mean(cars()$mpg), 1)) + output$wt <- renderText(paste(round(mean(cars()$wt) * 1000), "lb")) + output$plot <- renderPlot({ + ggplot(cars(), aes(wt * 1000, mpg, colour = factor(cyl))) + + geom_point(size = 3) + + labs(x = "Weight (lb)", y = "Miles per gallon", colour = "Cylinders") + + theme_minimal(base_size = 14) + }) + output$data <- renderTable(cars(), rownames = TRUE) +} + +shinyApp(ui, server) diff --git a/content/blog/shiny-r-1-15/_screenshot-src/before-app/app.R b/content/blog/shiny-r-1-15/_screenshot-src/before-app/app.R new file mode 100644 index 000000000..8f1cd48ad --- /dev/null +++ b/content/blog/shiny-r-1-15/_screenshot-src/before-app/app.R @@ -0,0 +1,58 @@ +# The same app as ../after-app, written with the habits the shiny-for-r skill +# steers agents away from: nested fluidRow()/column() grids, and tabs faked +# with buttons and conditionalPanel(). +library(shiny) + +ui <- fluidPage( + titlePanel("Fuel economy"), + fluidRow( + column( + 3, + wellPanel( + checkboxGroupInput("cyl", "Cylinders", c(4, 6, 8), selected = c(4, 6, 8)), + sliderInput("hp", "Horsepower", 50, 340, c(50, 340)) + ) + ), + column( + 9, + fluidRow( + column(4, h4("Cars"), textOutput("n")), + column(4, h4("Average mpg"), textOutput("mpg")), + column(4, h4("Average weight"), textOutput("wt")) + ), + fluidRow( + column( + 12, + actionButton("show_plot", "Plot"), + actionButton("show_data", "Data") + ) + ), + fluidRow( + column( + 12, + conditionalPanel("output.view == 'plot'", plotOutput("plot")), + conditionalPanel("output.view == 'data'", tableOutput("data")) + ) + ) + ) + ) +) + +server <- function(input, output, session) { + view <- reactiveVal("plot") + observeEvent(input$show_plot, view("plot")) + observeEvent(input$show_data, view("data")) + output$view <- renderText(view()) + outputOptions(output, "view", suspendWhenHidden = FALSE) + + cars <- reactive({ + mtcars[mtcars$cyl %in% input$cyl & mtcars$hp >= input$hp[1] & mtcars$hp <= input$hp[2], ] + }) + output$n <- renderText(nrow(cars())) + output$mpg <- renderText(round(mean(cars()$mpg), 1)) + output$wt <- renderText(paste(round(mean(cars()$wt) * 1000), "lb")) + output$plot <- renderPlot(plot(cars()$wt, cars()$mpg, xlab = "wt", ylab = "mpg")) + output$data <- renderTable(cars(), rownames = TRUE) +} + +shinyApp(ui, server) diff --git a/content/blog/shiny-r-1-15/_screenshot-src/capture.py b/content/blog/shiny-r-1-15/_screenshot-src/capture.py new file mode 100644 index 000000000..d8ede15c9 --- /dev/null +++ b/content/blog/shiny-r-1-15/_screenshot-src/capture.py @@ -0,0 +1,70 @@ +"""Regenerate skill-before.png and skill-after.png from the two example apps. + +Runs before-app/ and after-app/ with Shiny for R, screenshots each one, and +writes the images to the post directory (the parent of this folder). + +Each image gets a 1px border so the mostly-white screenshot reads as one +object on the page background. + +Usage (requires R with shiny, bslib and ggplot2): + + uv run --with playwright --with pillow python capture.py +""" + +import pathlib +import socket +import subprocess +import time +import urllib.request + +from PIL import Image, ImageOps +from playwright.sync_api import sync_playwright + +HERE = pathlib.Path(__file__).parent +POST_DIR = HERE.parent + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def shoot(page, app: str, out: str) -> None: + port = free_port() + proc = subprocess.Popen( + ["Rscript", "-e", f"shiny::runApp('{HERE / app}', port = {port})"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + url = f"http://127.0.0.1:{port}/" + for _ in range(60): + try: + urllib.request.urlopen(url, timeout=1) + break + except OSError: + time.sleep(0.5) + else: + raise SystemExit(f"{app} did not start") + page.goto(url) + page.wait_for_selector("#plot img") + page.wait_for_timeout(1000) + page.screenshot(path=str(POST_DIR / out)) + img = Image.open(POST_DIR / out).convert("RGB") + ImageOps.expand(img, border=2, fill="#DEE2E6").save(POST_DIR / out) + finally: + proc.terminate() + proc.wait() + + +with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page( + viewport={"width": 1000, "height": 680}, device_scale_factor=2 + ) + shoot(page, "before-app", "skill-before.png") + shoot(page, "after-app", "skill-after.png") + browser.close() + +print(f"skill-before.png and skill-after.png written to {POST_DIR}") diff --git a/content/blog/shiny-r-1-15/autoreload.gif b/content/blog/shiny-r-1-15/autoreload.gif new file mode 100644 index 000000000..bea067aba Binary files /dev/null and b/content/blog/shiny-r-1-15/autoreload.gif differ diff --git a/content/blog/shiny-r-1-15/feature.png b/content/blog/shiny-r-1-15/feature.png new file mode 100644 index 000000000..2954a58b1 Binary files /dev/null and b/content/blog/shiny-r-1-15/feature.png differ diff --git a/content/blog/shiny-r-1-15/index.md b/content/blog/shiny-r-1-15/index.md new file mode 100644 index 000000000..ddf303901 --- /dev/null +++ b/content/blog/shiny-r-1-15/index.md @@ -0,0 +1,162 @@ +--- +title: Shiny for R 1.15 +date: 2026-11-23T00:00:00.000Z +people: + - Barret Schloerke +description: > + Shiny for R v1.15 is on CRAN! The package now ships an Agent Skill that + teaches coding agents how to write Shiny apps, autoreload works out of the + box, and sessions behave better when a page is refreshed or reconnected. +image: feature.png +image-alt: >- + Shiny for R 1.15: a card lists the topics covered by the bundled shiny-for-r + agent skill, next to cards for installing the skill into a project with btw + and for autoreload with watcher +topics: + - Interactive Apps +software: + - shiny-r + - btw + - watcher +languages: + - R +source: shiny +--- + + +We're happy to announce that [Shiny for R v1.15](https://cran.r-project.org/package=shiny) is now on CRAN! + +``` r +install.packages("shiny") +``` + +The highlights: + +- a bundled [Agent Skill](#agent-skill) teaches coding agents how to write Shiny for R apps, +- [autoreload](#autoreload-out-of-the-box) no longer needs an extra package install, and +- sessions are [steadier when a page is refreshed or reconnected](#refresh-and-reconnect). + +This is a small release: one new feature, and a round of fixes for things that came up after v1.14. Full details are in the [Shiny for R release notes](https://shiny.posit.co/r/reference/shiny/1.15.0/upgrade.html). + +## Agent skill + +When we [shipped agent skills in Shiny for Python v1.7](../../blog/2026-08-04_shiny-r-1-14-python-1-7/#agent-skills), we said they were coming to R soon. They're here! + +Coding agents write a lot of Shiny apps, and they tend to make the same mistakes: nested `fluidRow()` and `column()` pyramids instead of a bslib layout, tabs faked with buttons and `conditionalPanel()`, slow work that blocks all user sessions, and `print()` calls in place of a debugger. Shiny v1.15 ships a `shiny-for-r` skill that follows the [Agent Skills](https://agentskills.io) convention and steers agents toward what the framework already provides. + +To show the difference, here is one small app written both ways. The data, inputs, and outputs are the same; only the choice of layout and navigation changes. + +
+The habits above: a fluidRow() and column() grid, with two buttons and conditionalPanel() standing in for tabs. + +
+ +
+What the skill points to: a bslib page with a sidebar, value boxes, and a card with real tabs. + +
+ +The skill is an index. Its `SKILL.md` is a short table of topics, and each row points to one of 21 reference files. An agent reads the index, then opens only the one or two references its task touches: + +| Area | References | +|------------------------------------|------------------------------------| +| Foundations | reactivity, modules, session lifecycle | +| Async | promises, `ExtendedTask` | +| Dashboards | dashboard design, bslib components, layouts | +| Navigation and dynamic UI | navigation, dynamic UI | +| Outputs | plots, tables, files | +| Feedback and state | notifications and validation, bookmarking | +| Theming and extending | theming and assets, custom components | +| Testing and observability | `testServer()`, debugging, OpenTelemetry, ecosystem | + +### Using the skill + +Agents that use [btw](https://posit-dev.github.io/btw/) find the skill on their own. btw looks for skills in every attached package, so once your session has run `library(shiny)`, the skill is available. There is nothing to install. + +To use the skill with Claude Code or another skill-aware tool, copy it into your project: + +``` r +btw::btw_skill_install_package("shiny") +``` + +By default this copies the skill into your project's `.btw/skills/` or `.agents/skills/` folder. Use `scope` to pick a different place, such as `scope = ".claude/skills"` for Claude Code or `scope = "user"` to make the skill available in all of your projects. + +Because the skill ships inside the package, it matches the version of Shiny you have installed. It's also tested with the package: every code example must parse, and every Shiny function it names must still be exported, so a renamed function fails our checks instead of misleading your agent. + +You can read the skill yourself, too. It lives at `system.file("skills", "shiny-for-r", package = "shiny")`. + +## Autoreload out of the box + +With `options(shiny.autoreload = TRUE)` (or [`devmode()`](https://shiny.posit.co/r/reference/shiny/latest/devmode.html)), Shiny reloads your app in the browser each time you save a file. Until now, Shiny used the [watcher](../../blog/2026-06-29_watcher-0-2-0/) package to do this only when it was installed, and fell back to an older, slower method that checked your files on a timer when it wasn't. + +In v1.15, watcher is a required dependency and the fallback is gone. Now, the operating system tells Shiny when a file changes, so there is no polling and no extra package to install. + +``` r +options(shiny.autoreload = TRUE) +shiny::runApp("myapp") +``` + +
+Each save of app.R reloads the app in the browser. + +
+ +The `shiny.autoreload.interval` and `shiny.autoreload.pattern` options work as before. + +## Refresh and reconnect + +Shiny v1.14 added [`session$destroy()`](../../blog/2026-08-04_shiny-r-1-14-python-1-7/#module-cleanup) for cleaning up dynamic modules. That work had a side effect we didn't intend, and it led us to a second, older bug nearby. Both are fixed in v1.15. + +### Async work that outlives the page + +In v1.14, closing a session destroyed every reactive value and expression created in it. It sounds tidy, but async work often finishes *after* the browser has gone away. If you happen to refresh the page while an [`ExtendedTask`](https://shiny.posit.co/r/reference/shiny/latest/ExtendedTask.html) is running, you'd see an error like this in your R console when the task settled: + +``` text +Can't access reactive `Theme Counter`; +its module session has been destroyed +``` + +The same thing happened with any promise or `later()` callback that read or set a reactive after the session closed. You could not always fix it yourself, since the read was often inside a package such as bslib or shinychat, not your app. + +In v1.15, closing a session and destroying one are two different things: + +- When a session **closes**, its reactives stay readable at their last value, and R's garbage collector reclaims them later. Late async work finishes quietly. Observers are still destroyed, so a late write can't wake the session back up. +- When you call **`session$destroy()`** on a live session, everything is torn down as before, and reading a destroyed reactive is still an error. In that case, a stale read is a real bug that you want to hear about. + +`onDestroy()` callbacks run in both cases, so your module cleanup code needs no changes. + +### Outputs after a reconnect + +If your app uses [`session$allowReconnect()`](https://shiny.posit.co/r/reference/shiny/latest/session.html), a browser that loses its connection can connect again to a new session. The browser kept its record of each output's state from the old session, though, so the first messages from the new session looked out of order. The browser console filled with errors like + +``` text +the output is in an unexpected state of: 'value' +``` + +Additionally, outputs kept showing results from the old session until something made them update again. + +The browser now resets its output state when it reconnects. + +## Other improvements + +A few more changes worth a quick mention. The full list is in the [release notes](https://shiny.posit.co/r/reference/shiny/1.15.0/upgrade.html): + +- [`dateInput()`](https://shiny.posit.co/r/reference/shiny/latest/dateInput.html)'s `datesdisabled` now works when `format` is not the default `yyyy-mm-dd`. For example, `dateInput("day", "Day", format = "mm/dd/yyyy", datesdisabled = "2026-11-26")` now disables November 26 as you'd expect. +- `dateInput(language =)` now loads its locale when `options(shiny.minified = FALSE)` is set, instead of falling back to English. +- `callModule()`, `moduleServer()`, `testServer()`, and `session$destroy()` work again with module ids that are character vectors. The parts are joined the same way `NS()` joins them, so `c("a", "b")` becomes `"a-b"`. Since v1.14 these failed with `` Invalid `namespace` ``. +- `invalidateLater()`, `reactivePoll()`, and `reactiveTimer()` work again with a custom session object that has no `onDestroy()` method. Since v1.14 they failed with `attempt to apply non-function`. +- `runApp()` now prints its `Listening on http://…` message only after the port is open, so tools that wait for that message can connect right away. (Thanks, [@nbenn](https://github.com/nbenn)!) +- A session whose outputs throw an unhandled error while being flushed is now closed, instead of the error escaping to the server loop. +- [`testServer()`](https://shiny.posit.co/r/reference/shiny/latest/testServer.html) gives clearer errors when a `downloadHandler()`'s `content` function writes no file, and when it is handed a function that is neither a server nor a module server. It also removes a module's outputs and downloads when `session$destroy(id)` is called. +- `ExtendedTask`'s OpenTelemetry output is more complete: the "add to queue" log now has its message, and invocations that waited behind a running one now get their own span. +- The server now rejects malformed websocket messages. A request for an unknown session method gets an `Unknown method` error response, and a message whose `method` is not a single string is refused. + +## In closing + +We're excited to see what you (and your agents) build with this release. As always, if you have questions or feedback, [join us on Discord](https://discord.gg/yMGCamUMnS) or open an issue on [rstudio/shiny](https://github.com/rstudio/shiny/issues/new). Happy Shiny-ing! + +## Acknowledgements + +A big thank you to all the folks who helped make this release happen by opening issues and contributing code: + +[@000wahab000](https://github.com/000wahab000), [@BajczA475](https://github.com/BajczA475), [@christophsax](https://github.com/christophsax), [@cpsievert](https://github.com/cpsievert), [@djacob65](https://github.com/djacob65), [@gadenbuie](https://github.com/gadenbuie), [@JamesStewartRE](https://github.com/JamesStewartRE), [@jeis4wpi](https://github.com/jeis4wpi), [@josefelipe0036](https://github.com/josefelipe0036), [@JosiahParry](https://github.com/JosiahParry), [@karangattu](https://github.com/karangattu), [@LeonidasZhak](https://github.com/LeonidasZhak), [@ml-ebs-ext](https://github.com/ml-ebs-ext), [@nbenn](https://github.com/nbenn), [@roberson4627-cpu](https://github.com/roberson4627-cpu), [@schloerke](https://github.com/schloerke), [@shelbylevel](https://github.com/shelbylevel), [@shikokuchuo](https://github.com/shikokuchuo), [@taekop](https://github.com/taekop), and [@vedhav](https://github.com/vedhav). diff --git a/content/blog/shiny-r-1-15/index.qmd b/content/blog/shiny-r-1-15/index.qmd new file mode 100644 index 000000000..6628ed798 --- /dev/null +++ b/content/blog/shiny-r-1-15/index.qmd @@ -0,0 +1,155 @@ +--- +title: "Shiny for R 1.15" +date: 2026-11-23 +people: + - Barret Schloerke +description: > + Shiny for R v1.15 is on CRAN! The package now ships an Agent Skill that + teaches coding agents how to write Shiny apps, autoreload works out of the + box, and sessions behave better when a page is refreshed or reconnected. +image: "feature.png" +image-alt: "Shiny for R 1.15: a card lists the topics covered by the bundled shiny-for-r agent skill, next to cards for installing the skill into a project with btw and for autoreload with watcher" +topics: + - Interactive Apps +software: + - shiny-r + - btw + - watcher +languages: + - R +source: shiny +--- + +We're happy to announce that [Shiny for R v1.15](https://cran.r-project.org/package=shiny) is now on CRAN! + +```r +install.packages("shiny") +``` + +The highlights: + +* a bundled [Agent Skill](#agent-skill) teaches coding agents how to write Shiny for R apps, +* [autoreload](#autoreload-out-of-the-box) no longer needs an extra package install, and +* sessions are [steadier when a page is refreshed or reconnected](#refresh-and-reconnect). + +This is a small release: one new feature, and a round of fixes for things that came up after v1.14. Full details are in the [Shiny for R release notes](https://shiny.posit.co/r/reference/shiny/1.15.0/upgrade.html). + + +## Agent skill + +When we [shipped agent skills in Shiny for Python v1.7](/blog/2026-08-04_shiny-r-1-14-python-1-7/#agent-skills), we said they were coming to R soon. They're here! + +Coding agents write a lot of Shiny apps, and they tend to make the same mistakes: nested `fluidRow()` and `column()` pyramids instead of a bslib layout, tabs faked with buttons and `conditionalPanel()`, slow work that blocks all user sessions, and `print()` calls in place of a debugger. Shiny v1.15 ships a `shiny-for-r` skill that follows the [Agent Skills](https://agentskills.io) convention and steers agents toward what the framework already provides. + +To show the difference, here is one small app written both ways. The data, inputs, and outputs are the same; only the choice of layout and navigation changes. + +![The habits above: a `fluidRow()` and `column()` grid, with two buttons and `conditionalPanel()` standing in for tabs.](skill-before.png){fig-alt="A plain Shiny app titled Fuel economy. A grey box of inputs sits on the left. Three numbers are shown as plain text under small headings, above two buttons labelled Plot and Data and an unstyled scatterplot."} + +![What the skill points to: a bslib page with a sidebar, value boxes, and a card with real tabs.](skill-after.png){fig-alt="The same Fuel economy app as a bslib dashboard. Inputs sit in a sidebar. Three value boxes show the numbers in large type, above a card with Plot and Data tabs that holds a coloured scatterplot."} + +The skill is an index. Its `SKILL.md` is a short table of topics, and each row points to one of 21 reference files. An agent reads the index, then opens only the one or two references its task touches: + +| Area | References | +|---|---| +| Foundations | reactivity, modules, session lifecycle | +| Async | promises, `ExtendedTask` | +| Dashboards | dashboard design, bslib components, layouts | +| Navigation and dynamic UI | navigation, dynamic UI | +| Outputs | plots, tables, files | +| Feedback and state | notifications and validation, bookmarking | +| Theming and extending | theming and assets, custom components | +| Testing and observability | `testServer()`, debugging, OpenTelemetry, ecosystem | + +### Using the skill + +Agents that use [btw](https://posit-dev.github.io/btw/) find the skill on their own. btw looks for skills in every attached package, so once your session has run `library(shiny)`, the skill is available. There is nothing to install. + +To use the skill with Claude Code or another skill-aware tool, copy it into your project: + +```r +btw::btw_skill_install_package("shiny") +``` + +By default this copies the skill into your project's `.btw/skills/` or `.agents/skills/` folder. Use `scope` to pick a different place, such as `scope = ".claude/skills"` for Claude Code or `scope = "user"` to make the skill available in all of your projects. + +Because the skill ships inside the package, it matches the version of Shiny you have installed. It's also tested with the package: every code example must parse, and every Shiny function it names must still be exported, so a renamed function fails our checks instead of misleading your agent. + +You can read the skill yourself, too. It lives at `system.file("skills", "shiny-for-r", package = "shiny")`. + + +## Autoreload out of the box + +With `options(shiny.autoreload = TRUE)` (or [`devmode()`](https://shiny.posit.co/r/reference/shiny/latest/devmode.html)), Shiny reloads your app in the browser each time you save a file. Until now, Shiny used the [watcher](/blog/2026-06-29_watcher-0-2-0/) package to do this only when it was installed, and fell back to an older, slower method that checked your files on a timer when it wasn't. + +In v1.15, watcher is a required dependency and the fallback is gone. Now, the operating system tells Shiny when a file changes, so there is no polling and no extra package to install. + +```r +options(shiny.autoreload = TRUE) +shiny::runApp("myapp") +``` + +![Each save of `app.R` reloads the app in the browser.](autoreload.gif){fig-alt="An animation with an editor showing app.R on the left and a browser showing the running app on the right. A line that sets the histogram colour is edited and saved, and the histogram in the browser turns from blue to red. Then the heading text is edited and saved, and the heading in the browser changes to match."} + +The `shiny.autoreload.interval` and `shiny.autoreload.pattern` options work as before. + + +## Refresh and reconnect + +Shiny v1.14 added [`session$destroy()`](/blog/2026-08-04_shiny-r-1-14-python-1-7/#module-cleanup) for cleaning up dynamic modules. That work had a side effect we didn't intend, and it led us to a second, older bug nearby. Both are fixed in v1.15. + +### Async work that outlives the page + +In v1.14, closing a session destroyed every reactive value and expression created in it. It sounds tidy, but async work often finishes *after* the browser has gone away. If you happen to refresh the page while an [`ExtendedTask`](https://shiny.posit.co/r/reference/shiny/latest/ExtendedTask.html) is running, you'd see an error like this in your R console when the task settled: + +```text +Can't access reactive `Theme Counter`; +its module session has been destroyed +``` + +The same thing happened with any promise or `later()` callback that read or set a reactive after the session closed. You could not always fix it yourself, since the read was often inside a package such as bslib or shinychat, not your app. + +In v1.15, closing a session and destroying one are two different things: + +* When a session **closes**, its reactives stay readable at their last value, and R's garbage collector reclaims them later. Late async work finishes quietly. Observers are still destroyed, so a late write can't wake the session back up. +* When you call **`session$destroy()`** on a live session, everything is torn down as before, and reading a destroyed reactive is still an error. In that case, a stale read is a real bug that you want to hear about. + +`onDestroy()` callbacks run in both cases, so your module cleanup code needs no changes. + +### Outputs after a reconnect + +If your app uses [`session$allowReconnect()`](https://shiny.posit.co/r/reference/shiny/latest/session.html), a browser that loses its connection can connect again to a new session. The browser kept its record of each output's state from the old session, though, so the first messages from the new session looked out of order. The browser console filled with errors like + +```text +the output is in an unexpected state of: 'value' +``` + +Additionally, outputs kept showing results from the old session until something made them update again. + +The browser now resets its output state when it reconnects. + + +## Other improvements + +A few more changes worth a quick mention. The full list is in the [release notes](https://shiny.posit.co/r/reference/shiny/1.15.0/upgrade.html): + +- [`dateInput()`](https://shiny.posit.co/r/reference/shiny/latest/dateInput.html)'s `datesdisabled` now works when `format` is not the default `yyyy-mm-dd`. For example, `dateInput("day", "Day", format = "mm/dd/yyyy", datesdisabled = "2026-11-26")` now disables November 26 as you'd expect. +- `dateInput(language =)` now loads its locale when `options(shiny.minified = FALSE)` is set, instead of falling back to English. +- `callModule()`, `moduleServer()`, `testServer()`, and `session$destroy()` work again with module ids that are character vectors. The parts are joined the same way `NS()` joins them, so `c("a", "b")` becomes `"a-b"`. Since v1.14 these failed with ``Invalid `namespace` ``. +- `invalidateLater()`, `reactivePoll()`, and `reactiveTimer()` work again with a custom session object that has no `onDestroy()` method. Since v1.14 they failed with `attempt to apply non-function`. +- `runApp()` now prints its `Listening on http://…` message only after the port is open, so tools that wait for that message can connect right away. (Thanks, [@nbenn](https://github.com/nbenn)!) +- A session whose outputs throw an unhandled error while being flushed is now closed, instead of the error escaping to the server loop. +- [`testServer()`](https://shiny.posit.co/r/reference/shiny/latest/testServer.html) gives clearer errors when a `downloadHandler()`'s `content` function writes no file, and when it is handed a function that is neither a server nor a module server. It also removes a module's outputs and downloads when `session$destroy(id)` is called. +- `ExtendedTask`'s OpenTelemetry output is more complete: the "add to queue" log now has its message, and invocations that waited behind a running one now get their own span. +- The server now rejects malformed websocket messages. A request for an unknown session method gets an `Unknown method` error response, and a message whose `method` is not a single string is refused. + + +## In closing + +We're excited to see what you (and your agents) build with this release. As always, if you have questions or feedback, [join us on Discord](https://discord.gg/yMGCamUMnS) or open an issue on [rstudio/shiny](https://github.com/rstudio/shiny/issues/new). Happy Shiny-ing! + + +## Acknowledgements + +A big thank you to all the folks who helped make this release happen by opening issues and contributing code: + +[@000wahab000](https://github.com/000wahab000), [@BajczA475](https://github.com/BajczA475), [@christophsax](https://github.com/christophsax), [@cpsievert](https://github.com/cpsievert), [@djacob65](https://github.com/djacob65), [@gadenbuie](https://github.com/gadenbuie), [@JamesStewartRE](https://github.com/JamesStewartRE), [@jeis4wpi](https://github.com/jeis4wpi), [@josefelipe0036](https://github.com/josefelipe0036), [@JosiahParry](https://github.com/JosiahParry), [@karangattu](https://github.com/karangattu), [@LeonidasZhak](https://github.com/LeonidasZhak), [@ml-ebs-ext](https://github.com/ml-ebs-ext), [@nbenn](https://github.com/nbenn), [@roberson4627-cpu](https://github.com/roberson4627-cpu), [@schloerke](https://github.com/schloerke), [@shelbylevel](https://github.com/shelbylevel), [@shikokuchuo](https://github.com/shikokuchuo), [@taekop](https://github.com/taekop), and [@vedhav](https://github.com/vedhav). diff --git a/content/blog/shiny-r-1-15/skill-after.png b/content/blog/shiny-r-1-15/skill-after.png new file mode 100644 index 000000000..9cade24da Binary files /dev/null and b/content/blog/shiny-r-1-15/skill-after.png differ diff --git a/content/blog/shiny-r-1-15/skill-before.png b/content/blog/shiny-r-1-15/skill-before.png new file mode 100644 index 000000000..fe211561c Binary files /dev/null and b/content/blog/shiny-r-1-15/skill-before.png differ