Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Preface

Who This Book Is For and What You Need to Know

This book is for .NET developers who want to use the C# skills they already have to build interactive UIs.

You do not need to have written front-end code. How components are laid out, how styles are adjusted, how requests are sent and how the page updates are all handled by Gradio.NET; what you write is a C# method that takes input and returns a result, plus a few lines that wire it to the UI. You do not need to know Python either. Every example in this book is C#, and the Python version of Gradio is not involved.

What you do need is C# itself, including generics, nullable reference types and everyday collection operations. For asynchronous programming, you should be able to read async/await and Task; the book uses them heavily from Chapter 16 on, and barely at all in the first fifteen chapters. You should also have a basic grasp of HTTP: what a request and a response are, what a status code means, and what happens when a browser opens an address. ASP.NET Core experience helps — Chapter 21 mounts an application directly on it — but not having it does not affect the first twenty chapters.

The book does not require any of the following: experience with web front-end frameworks, machine learning knowledge, or databases. Chapter 16 connects to a real model service, but that chapter is about streaming output, not machine learning.

Software Versions and Target Framework

Every example is based on the Gradio.Net NuGet package 0.6.30.8 and targets net10.0.

The target framework net10.0 requires the .NET 10 SDK. Run dotnet --version on the command line; the output should start with 10.. The global.json at the repository root pins the SDK’s major version and roll-forward policy, so a machine with several SDKs installed will not silently switch to another major version. If that command reports that no matching SDK was found, install the .NET 10 SDK before continuing.

Beyond .NET itself, the examples need no Python, no separate front-end build and no Node.js. Gradio.NET ships its front-end assets with the NuGet package.

Where the Chapter Samples Are and How to Get Them

Each chapter has its own sample project. In this English edition they live in samples-en\chapterNN — Chapter 5, for example, is in samples-en\chapter05.

“Own” means this. Take any one chapter’s directory and you can run it without having done the earlier chapters. Each sample carries every source file, configuration file, sample data file and pinned dependency version it needs, and does not depend on other chapters through project references, linked files or runtime paths. You can unpack only the Chapter 12 material, skip the first eleven chapters, and it still builds and runs.

A chapter’s sample shows the state of the application as of that chapter. It contains the modules explained in earlier chapters, but not things that only come up later. So the Chapter 12 sample is a working workbench with the earlier modules already installed, not an empty shell that only demonstrates file upload. That way, when you read a chapter, all the code you see has already been explained.

The code snippets in the main text all come from these sample projects. A snippet is trimmed to make one point clear, but the trimmed code still compiles inside that chapter’s project; where a piece of illustrative code cannot compile, the text says explicitly that it is illustrative.

One Way to Restore, Build, Launch and Stop

All chapters use the same set of commands; only the project name changes. The commands below run in Windows PowerShell from the repository root, using Chapter 5 as the example.

dotnet restore samples-en\chapter05\Chapter05.csproj
dotnet build samples-en\chapter05\Chapter05.csproj --configuration Release --no-restore
dotnet run --project samples-en\chapter05\Chapter05.csproj --configuration Release --no-build --no-restore

Each of the three commands does one thing. restore fetches dependencies. build compiles, and --no-restore means it does not repeat the restore. run launches the application, and --no-build and --no-restore mean it uses the output of the previous step directly.

Once it starts, the console prints an address.

Running on local URL: http://127.0.0.1:7860/

Open that address in a browser and you have the application’s UI. Stop it with Ctrl+C; once the process exits, the port is released.

For other chapters, replace chapter05 and Chapter05 in the commands with the corresponding chapter number; everything else stays the same. The book does not repeat these three commands chapter by chapter.

Each sample pins Gradio.Net to 0.6.30.8 in its PackageReference rather than using a version range, so restore gets exactly the version the sample locks. The samples ship no lock file, and you are not required to understand lock files first.

The Chapter 16 sample needs a connection to an OpenAI-compatible model service. Its address and credentials are supplied at runtime through environment variables; the chapter gives the variable names and how to use them. These values are not written into code, configuration files or sample data, and are not distributed with the repository. Without them, the sample reports the missing configuration and stops — it does not invent a reply.

Port Conflicts and Common Startup Problems

The default port is 7860. If it is already in use — most often because an application you started earlier has not been stopped — startup fails and prints:

System.IO.IOException: Failed to bind to address http://127.0.0.1:7860: address already in use.

The process then exits rather than hanging. First find out what is holding the port.

Get-NetTCPConnection -LocalPort 7860 -State Listen | Select-Object OwningProcess
Get-Process -Id <process ID from the previous command>

Decide only after you know which process it is. If it is an application you started, stop it; if it belongs to someone else or to other software, do not stop it — use a different port instead. Pass the port in when launching:

demo.Launch(serverPort: 7861);

Besides ports, there are two other classes of problem worth knowing up front.

The first is a failed dependency restore. Most often a package cannot be found, which is usually a NuGet source configuration issue; check the output of dotnet nuget list source for a usable source. Next most common is a version conflict, usually because you edited the PackageReference in the project file; change it back to 0.6.30.8 and restore again.

The second is an SDK version mismatch. The error message mentions global.json and the required major version. Install the SDK it asks for, or use dotnet --list-sdks to see exactly which versions are on your machine.

The book has no separate appendix for these problems; come back to this section when you hit one.

How to Read the API Snippets in the Text

The text writes code in C#. Components are created through the factory methods under gr, for example gr.Textbox() and gr.Blocks(). Parameter names match the library’s public parameters, so you can compare them directly.

Look at the return type first. In Gradio.NET the most common mistake is a mismatch between what a handler function returns and what an output component expects. When a component is first introduced, the book states explicitly what type it passes to the handler function and what type it accepts back; that is not repeated later.

Next, check whether this is where the capability first appears. The book advances by capability, and each concept is explained in detail only in the chapter where it is introduced. Later mentions give a chapter number instead of explaining it again. If you meet an unexplained type in a chapter, going back to where it first appeared is usually faster than looking for an explanation there.

Read the sentence outside the code block too. What a parameter actually does, where its boundaries are and how it fails are often invisible in the code — whether a limit rejects or truncates, whether an event coalesces or drops. Those conclusions sit beside the code and come from running it, not from guesswork.

This book covers only the public API and observable behavior; it does not dissect the library’s internal implementation. Every behavior described here can be reproduced with the samples. Implementation details can change and are not a promise. Where the book has not verified something, the text says so rather than stating it as a conclusion.

The references at the end of the book list the addresses used to check APIs and protocols: the package page, the source repository, the XML documentation inside the package, and the official documentation for .NET, ASP.NET Core and OpenAI-compatible interfaces. When a behavior in the text comes from those documents rather than from a run, the text says so.

A Note on This English Edition

This edition is a full translation of the Chinese original. Nothing is left in Chinese: the sample data, example strings, API names, C# identifiers and every figure have been reworked for English readers.

The sample data is English. The workbench examples wrap, count and split English text by character. The English corpus was written so that every line length, character count, truncation position and quoted output fragment in the book still matches what the samples actually produce. This applies to SampleText values, the assets/*.txt and assets/*.csv files, and the strings shown as the output of those operations.

The screenshots and diagrams were regenerated from the English samples, so all UI text visible in a figure is English. Figure captions describe what the figure shows.

All sample projects for this edition live in samples-en/, a copy of samples/ with code comments, UI strings, sample data, identifiers, API names and project metadata translated. File names, versions and command-line syntax are unchanged, so the code you read here compiles against the same Gradio.Net 0.6.30.8 package as the Chinese edition. Use the samples-en paths in every command.

Chapter 1. Getting to Know Gradio.NET

You finish writing a C# method, and the real trouble is only just beginning: how do you get other people to use it.

This is a delivery problem. A method that runs on its own does not mean other people can actually use it. This chapter does not go into implementation; it first makes clear what problem Gradio.NET simplifies and which scenarios it suits, then sets out what this book plans to help you build.

1.1 From C# Handler Functions to an Interactive Web UI

Suppose you have written a method. It takes a piece of text, removes extra whitespace, and returns the cleaned result. The logic is not complicated, under thirty lines.

To let a colleague use it, there are three paths you can take.

The first is to send over the source code and let the other person compile it themselves. This path only holds for colleagues who have the .NET SDK installed, and they also have to know how to pass the arguments in. In most cases, they would rather just make the change by hand.

The second is to make it a console app. That is already much better than sending source code; a double-click runs it. But it is still awkward to use. Arguments have to be given in order, and if you get one wrong all you can do is read the error; there is no validation of the input, and stuffing a whole piece of text with line breaks into a single argument takes some effort; every time you change the input you have to run it again, and the previous result disappears along with the window; when there is more than one input, you also have to remember which argument corresponds to which item.

The third is to make it a web page. An input box, a button, a result area — anyone can use them, and you can change things and look again as often as you like. The cost is the amount of work. You have to write a backend interface and wrap the method as an HTTP endpoint; write a frontend page that collects the input and sends it off; handle request state and show a loading indicator while waiting; and then handle error cases. A small tool that could have been usable in an afternoon often turns into a week-long project because of this, and in the end it may still not be nicer to use than the console version.

Gradio.NET handles exactly the repetitive work on that third path.

What Gradio.NET does is not complicated. You write a C# method that takes input and returns a result, and it turns that method into a web page. Your code declares the input controls, buttons, and result area on the page, and your method decides what happens after a click; the framework takes care of the request, serialization, echoing back, and loading state in between.

Gradio.NET does not do the fine-grained interactions and animations of a frontend framework, nor the visual drag-and-drop building of a low-code platform. The UI is still written in code, just C# rather than HTML and JavaScript. What you write is still a method, only now with a clickable UI wrapped around it.

This positioning has one consequence. The UIs Gradio.NET produces all look more or less the same. It is good at putting a capability out there for people to use, and not good at turning the UI into a product differentiator. If the latter is your goal, this tool will feel constraining at every turn; if the former is your goal, it will save you a great deal of time.

1.2 Two Ways to Deliver the Same Processing Logic

This chapter’s sample is a text cleanup tool. There are only three rules. Remove the whitespace at the start and end of each line, coalesce consecutive whitespace within a line into a single space, and drop blank lines. After cleanup, count how many lines there are and how many characters.

These three rules live in a class library that does not reference Gradio.NET. Both the console version and the web version reference it, and neither writes its own copy. This is the premise for all the comparisons that follow. If the logic differed between the two sides, the comparison would be between two programs rather than between two ways of delivering one.

Figure 1-1 Two delivery forms of the same processing logic

Look at the console version first. After the build, pass the text in as an argument.

dotnet build samples-en\chapter01\console\Console.csproj --configuration Release
dotnet run --project samples-en\chapter01\console\Console.csproj --configuration Release --no-build -- "  First line   has extra spaces  "

The output is as follows.

First line has extra spaces

-- 1 lines, 23 characters

The result is correct. But this is what using it looks like. Open a terminal, go to the directory, type the command, look at the result; to change one character, press the up arrow to recall the command, move the cursor inside the quotes to edit, then press Enter. When the text gets long, the content inside the quotes starts to become hard to read; if the text contains line breaks, it is worse, because the command line treats a line break as the end of the command.

Now look at the web version. Launch this chapter’s sample and open 127.0.0.1:7860 in a browser.

Figure 1-2 The initial UI of the sample

Paste text on the left, get the result on the right. Change one character, click again, and the result updates immediately.

Figure 1-3 After pasting a piece of text with extra whitespace and clicking “Clean up”

With the same piece of text, the differences between the two delivery forms come down to five places.

How the input is given. The console makes you remember argument order and quotes; the web version is just pasting text into a box. This one looks like a mere matter of habit, but it has a large practical effect. Spaces and line breaks inside quotes are hard to make out by eye, whereas text pasted into an input box is preserved exactly as it is — what you see is what you get.

Where the result goes. The console result is squeezed into the same window as the output of the previous command, and you have to scroll down to find it; the web result stays fixed in the area on the right, overwritten on each change, so it never piles up. The longer the task runs, the more obvious this difference becomes.

What you see when something fails. The console prints an exception stack trace to the terminal, useful to the person writing the code and useless to the person using the tool; the web version at least does not make users think they broke the terminal.

The cost of repeating an operation. The console makes you type the command again; the web version only needs one more click. If you do something twenty times a day, that difference is the difference between twenty typed commands and twenty clicks.

Who can use it. Basically only the person who wrote the code will use the console version; anyone can use the web version. This one is often underestimated. If only the author can use a tool, it saves the author’s time; if others can use it, it saves the team’s time.

What the two sides compute is exactly the same, because the processing logic is one and the same code. The difference lies in where the input comes from, where the result goes, and how much it costs to do it once more.

The web version has a cost too. It adds a launch step. A console app runs on a double-click; the web version has to start the application first and then open a browser.

So the two delivery forms are not a case of the new replacing the old. For one-off, personal use with simple input, the console is less trouble; when others need to use it, when you need to adjust repeatedly, and when the input is a long piece of text or a file, the web version fits better. This chapter spends so much space on this comparison because you will meet the same question in every later chapter. In what form should this capability be handed to other people?

When you cannot work out how a feature should be designed, start by asking where its input comes from and who sees the result. Once those two questions are clear, what remains is mostly which components to choose and how to bind the events.

This chapter does not explain the code in the sample that declares the UI. Chapter 2 starts from the smallest application and goes through it line by line.

1.3 Where Gradio.NET Fits and Its Boundaries

To decide whether to use this tool, look at whether its value lies in “what the method does” or in “how the page moves”. The former suits it; the latter does not.

By that standard, the following kinds of scenarios are a good fit.

Turn the C# logic you already have into a UI you can operate. You may already have a pile of methods that process text, parse files, or call APIs, sitting in a class library or a console app that only you use. Wrapping a UI around them costs very little, and the payoff is that others can use them too.

Small personal tools on your local machine. The cleanup, checking, and conversion you repeat every day, turned into something finished with a few clicks on a page. Tools like this need no user system, no deployment to a server, and do not even need to stay open — you close them when done. This book’s main application belongs to this category.

Internal data checks and demos. Throw in a batch of data, compare the difference before and after processing, or lay out the results of an algorithm under several sets of parameters side by side. Gradio.NET puts these UIs together quickly, and changes to them are quick too.

Teaching and experimentation. If you want students or colleagues to understand what a method does, letting them change the input and see the output themselves is far more effective than reading the code.

The other way around, the following kinds of scenarios are not a good fit.

A product UI offered to the outside world. Multiple users, permissions, state isolation, frontend interaction details — these are not its strengths. It can do them, but you will find yourself working around it the whole time, and what you end up with neither looks like a product nor enjoys the framework’s convenience.

Cases where the UI itself is the selling point. Marketing pages, showcase pages that need delicate motion effects, and pages with a design spec demanding pixel-perfect reproduction are better done with a frontend framework.

Large applications that need complex frontend state management. Dozens of interdependent interaction states, pieced together with events and session state, quickly get out of control.

This book sets three explicit limits on its scope.

First, it targets personal use on your local machine only. All the samples run on your own machine, listening on the loopback address. There is no promise of sharing with several people on an intranet, no promise of public deployment, and nothing about product-grade concerns such as multi-tenancy or identity systems. Chapter 20 covers authentication, but that is “adding a door to a local app”, not “building a user system”.

Second, it is verified only on Windows. The samples, commands, and main flows were all actually run under Windows and .NET 10. The library itself is cross-platform, but the book will not state as a conclusion anything it has not verified on Linux or in a container.

Third, it covers only the public API and observable behavior. It does not dissect the library’s internal implementation, and does not treat implementation details as promises you can rely on. Every behavioral description can be reproduced with a sample; implementation details change, behavior does not change casually.

1.4 Getting to Know the Multi-Module Workbench That Runs Through the Book

This book is not a set of unrelated examples. From this chapter to the last, it builds the same thing. A personal workbench on your local machine, gathering the repetitive text and table processing of everyday use into one UI.

It has real repetitive work. Cleaning up a piece of text copied from somewhere else, checking an exported table, running a few files through the same set of rules. These things happen every week; once or twice does not matter, but a hundred times calls for a tool.

It needs enough different capabilities. Import, rules, preview, processing, export, save — each piece needs different components and different ways of interacting, which happens to put Gradio.NET’s component families, events, state, queues, and streaming output to use. A toy example could not cover all of this.

Its boundaries are clear. Personal, on the local machine, single-user, no service, with a manageable scale. Once the scope is clear, there is a basis for what each chapter adds and what it does not.

How the modules are divided matters too. Divide by “what the input is” and “how long one operation takes”, not by feature names. Whether the input is a piece of text, a choice, a table, or a few files decides which kind of component to use; whether the operation finishes in an instant or takes tens of seconds decides whether you need a queue, whether you need progress, and whether it can be cancelled. Divided along these lines, the boundaries between modules come out fairly natural, and when the mechanisms are explained later they will not feel forced.

Its final shape is shown in Figure 1-4.

Figure 1-4 The composition of the multi-module workbench and the chapters each part belongs to

This figure has three parts. At the top are the UI modules, the things you can see and click on the page, added gradually from Chapter 1 to Chapter 13. In the middle are the runtime mechanisms; they have no UI of their own, but they decide how modules remember state, how they queue, how the process is shown, and when it can be stopped — covered in Chapters 14 to 17. At the bottom are delivery-related capabilities that turn the workbench into a finished product other code can call — covered in Chapters 18 to 22.

Figure 1-4 is the goal, not the current state. All this chapter completes is the one piece in the top-left corner, text cleanup. That is also the only thing you see in the sample. Each later chapter adds one piece, and only at the end does the figure come together.

This arrangement has one advantage. In every chapter you see “what was added”, not “a different example”. The workbench is always there, just growing more complete.

One more convention should be stated up front. Each chapter’s sample is a snapshot “as of this chapter”. It contains the modules covered earlier and nothing that only comes up later. So when you get the Chapter 9 material, what you see is a workbench that runs and already has several modules in it, not an empty shell that only demonstrates a table. Reading this way, the code will not contain patterns you have not learned yet.

1.5 The Book’s Capability Map and Reading Paths

The book has 22 chapters, divided into five parts.

Part I — Building an Application Model, four chapters. Starting from the smallest application, you work out how a method becomes a UI, how values pass between components and handler functions, and how the UI is organized with containers. After these four chapters, you can write an application with the right structure.

Part II — Interface Building Blocks, nine chapters. Event binding first, then the various components: text and numeric inputs, selection, display, tables, charts and galleries, media, files, chat. This part is the body of the book and takes up forty percent of it, because components are the most substantial part of this library. Each chapter covers one family of components, spelling out what each is suited to, which parameters matter, and what types are passed to handler functions and returned from them.

Part III — Interaction Mechanisms, four chapters. State and sessions, queues and concurrency, streaming output and progress, cancellation and errors. These four chapters introduce no new components; they cover the mechanisms that make the UI “presentable” — why data is still there after a refresh, why clicking twice does not count twice, and how long tasks can show progress and be stopped partway.

Part IV — Shaping the Interface, three chapters. Splitting a single page into multiple pages, changing the theme, adding authentication. These three chapters are about the look and the boundaries of the workbench as a finished product.

Part V — Integration and Delivery, two chapters. Hooking into ASP.NET Core, and exposing the capabilities as an interface. After these two chapters, the capabilities on the workbench are no longer usable only through the page.

There are three ways to read it; choose according to your needs.

Read in order. From Chapter 1 to Chapter 22, each chapter’s explanation continues from the previous one; this is the least effort to read and the best way to feel the workbench being filled in bit by bit. If this is your first contact with the library, this is the recommended way.

Jump around as needed. Each chapter’s sample is independent: grab a chapter’s folder and you can run that chapter, with no need to finish the earlier ones first. If you only want to solve one specific problem, such as making a UI with a table, you can turn straight to Chapter 9. The price is that the chapter will reference concepts covered earlier, and you have to accept the “not explained again here” style.

Use it as a reference. From Chapter 5 onward, every chapter is organized by capability, and the chapters on component families are especially good for lookup. If you cannot remember what a parameter does, turning to the relevant section is faster than rereading the whole chapter.

Whichever you choose, these three reading conventions should be stated up front.

A concept is explained in detail only in the chapter where it is first introduced. When it comes up again later, the chapter number is given and it is not explained a second time. So when you see a type that has not been explained, flipping back is usually faster than hunting in place.

Key methods are given a full implementation when they first appear, especially the handler functions that carry this chapter’s state transitions. Methods shown in an earlier chapter and unchanged here are not pasted again; when they change, the full implementation after the change is pasted, along with a note on what changed.

Code snippets come from samples that actually run, trimmed to make a point clear, but the trimmed code can still be dropped into that chapter’s project and compiled. For illustrative code that cannot compile, the main text says explicitly that it is illustrative.

1.6 Chapter Summary

Gradio.NET solves the problem of “the method is written, how do you get people to use it”. It does not change your processing logic; it only changes where the input comes from and where the result goes.

To decide whether to use it, look at whether the tool’s value lies in the method itself or in the page’s presentation. Small personal tools on your local machine, internal checks and demos, and wrapping a UI around existing logic are what it is good at; for external products and cases where the UI is the selling point, it is not a fit.

The whole book revolves around one multi-module workbench, advancing by capability, with each chapter adding one piece. The first piece built in this chapter is text cleanup, and the twenty-some chapters that follow will fill it out into the shape shown in Figure 1-4.

The next chapter starts from the smallest application. One method, two inputs, one output, a few lines of code, and it runs.

Chapter 2. From Handler Functions to Interfaces

The text cleanup tool in Chapter 1 has an input box, a button, and a result area on its UI. Not one word in that chapter explained how these went from a C# method to a UI.

This chapter starts from the smallest application. The example is a tool that splits by a separator. A piece of text and a separator go in, multiple lines come out, empty segments are dropped, and the end reports how many segments there are in total.

It is not the cleanup tool from Chapter 1, nor is it the first module of the workbench. This chapter is about “how a handler function becomes a UI”, and a small application is the easiest way to do that; how the workbench is put together is left for Chapter 4.

2.1 Interface’s Inputs, Function, and Outputs

The whole application is about fifty lines.

using Gradio.Net;

static string Split(string text, string separator)
{
    if (string.IsNullOrWhiteSpace(text))
    {
        return "(no input)";
    }

    var parts = text.Split(
        string.IsNullOrEmpty(separator) ? "\n" : separator,
        StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

    if (parts.Length == 0)
    {
        return "(no segments to split)";
    }

    return string.Join("\n", parts) + $"\n\n-- {parts.Length} segments";
}

var source = gr.Textbox(
    label: "Text to split",
    value: "apples, bananas, oranges",
    lines: 6);

var separator = gr.Textbox(
    label: "Separator",
    value: ",");

var result = gr.Textbox(
    label: "Split result",
    lines: 8,
    interactive: false);

var demo = gr.Interface(
    Split,
    inputs: [source, separator],
    outputs: [result],
    title: "Split by Separator",
    description: "Split a piece of text into lines by a separator, and empty segments are dropped.",
    examples: new[]
    {
        new[] { "apples, bananas, oranges", "," },
        new[] { "first;second;third", ";" },
    },
    submitBtn: "Split",
    flaggingMode: "never",
    apiName: "split");

demo.Launch();

The code divides into four parts: one handler function, three components, one gr.Interface call, and one Launch. The last part is left for 2.5; look at the first three first.

The handler function is Split. It takes two strings and returns a string, and not one line in it is there for the UI framework to see. No HTTP, no HTML, and no idea whether a browser or something else is calling it. This division of labor is the foundation of the whole chapter: logic belongs to the function, the UI belongs to the components. Swap Split for any other function and the UI structure need not change; write the UI another way and the function need not change either. The more than twenty chapters that follow come back to this again and again. Modules in the workbench are swapped in and out, but the handler functions stay the same handler functions.

All three components are Textbox, but their position differs, and so does their role. The first two go into inputs, the last into outputs.

The components in inputs become the handler function’s parameters in order. source is first, and its current value is fed to text; separator is second, and its value is fed to separator. Order is the contract, and a contract that never reports an error. Swap the positions of these two Textboxes in inputs and Split still receives two strings, it compiles, it runs, only the results are all wrong. It treats the separator as the text to split. There is no hint for this kind of error; you just have to remember the order yourself.

The components in outputs receive the return values in order. Split returns one string, result is the only output component, and that string becomes the content of the result box. If the handler function needs to return two values, you need two output components, one for each; Chapter 3 expands on this.

Figure 2-1 The correspondence between Interface’s inputs, handler function, and outputs

What happens behind one click goes through four steps in order. The browser sends the current values of the two input boxes; the framework puts them into the parameter list in the order of inputs; Split is called; the returned string is written into result. Not one line of code here is written by you. No building a request, no serialization, and no logic to push the result back into the page. All you write is “what goes in, what comes out, and what is computed in between”.

This division of labor has another practical benefit: the handler function can be used on its own, away from the UI. Chapter 1 put the cleanup rules into a class library that does not reference Gradio.NET, and both the console version and the web version reference it — that is the extreme version of the same idea. This chapter’s Split is not extracted because it is too short; once the function in your hands grows past a hundred lines, or needs to be reused in two places, you should move it into a class library the way Chapter 1 did, leaving only a few lines of wiring code in the UI layer.

Launch this chapter’s sample with the three commands from the preface, and open 127.0.0.1:7860 in the browser.

Figure 2-2 The sample’s initial UI

The two input boxes already have content; that is the initial value given by the components’ value. The result area on the right is empty.

This is easy to misunderstand. The initial value is only filled into the input box; when the page opens it does not run the handler function once for you. Many people using it for the first time think a result should appear on the right first, then go looking for what they wrote wrong. Nothing is wrong; it simply does not run. To see a result, click the button.

Change the text to “red; green; blue; yellow”, the separator to “;”, and click “Split”.

Figure 2-3 After clicking “Split”

Four lines of results, with the last line being the segment count. That is all you can control on the UI: two input boxes, a submit button, and a result area. Below there are also the clear button and the examples table, covered in 2.3 and 2.4.

A few parameters in the code are still unexplained. title and description are the two lines of text at the top of the page; examples is the examples table below; submitBtn is the text on the button; flaggingMode turns off the “Flag” button that would otherwise appear by default; and apiName is completely invisible on the page.

These parameters fall into two groups by what they affect. One group decides what happens after you click; the other decides what extra things appear on the page. The first group is the focus of this chapter, covered in 2.3 and 2.4; the second group is title, description, the button text, the examples table, and the Flag button that appears by default — they change what the page looks like, not the result that gets computed. The discussion below follows this split instead of listing parameters. Listing them once is not something you will remember; you would have to come back and look them up when you use them.

apiName belongs to neither group, so let us get it out of the way first. It decides what this function is called when invoked as an interface. Given split, the interface is /split; without it, the library takes the handler function’s name, and this chapter’s handler function is written in top-level statements as a local function, so it cannot get a decent name and the endpoint becomes /lambda. What /gradio_api/info lists is /lambda. Only by switching to a static method TextOps.Split does the endpoint become /Split. That is why the sample writes apiName explicitly. You cannot see it in the browser; it only affects how the outside world calls this application, and Chapter 22 will make use of it.

2.2 Choosing Input and Output Components for the Handler Function

Why are all three components Textbox? Because all three of these things are text on the page.

When choosing a component, first look at what form it should take on the page. A piece of text, a number, a set of options, a table, a file — each has its own component. Decide what this value looks like on the UI first, then go find the matching one in the component family, and you usually get it right in one step. Do it the other way around — pick a component that looks nice first, then figure out how to cram the data in — and you always end up doing conversions somewhere, and the more conversions, the more room for error.

Following this line of thinking: a piece of text is Textbox, a number is Number, a set of options is Radio or Dropdown, a table is Dataframe, a file is File. What parameters each of these components has and where its boundaries lie are covered one by one starting in Chapter 6; this chapter only needs Textbox.

The three values in this chapter are all text, all use Textbox, but they are used differently and their parameters differ too.

The difference between an input component and an output component is not in the component itself, but in which side it is placed on. In the sample all three components are Textbox, the first two went into inputs and the last into outputs; move result into inputs and it becomes an ordinary input box. The same component can be both read and written; its position decides whether this time it feeds data or receives a result. Components placed in outputs are non-editable by default; to make one editable you have to write interactive: true explicitly.

label is for people to read. It appears above the input box and also in the header of the examples table. The handler function cannot see it. Split only knows it received two strings; it does not know what they are called.

value is the initial value, that is, the content pre-filled in the box when the page opens. The first two components both give one. The text cell is “apples, bananas, oranges”, the separator is “,”. The result box has none, because it should be empty the moment it opens; filling in an initial result would only make people think it was computed. The benefit of filling in an initial value is that the page is clickable as soon as it opens, with no need to think about what to type first.

lines decides how tall the box is, measured in lines. The text to split is given 6 lines, the separator is given the default 1 line. Because a separator is only one or two characters, giving it 6 lines would just waste screen space. This parameter only affects appearance, not what the handler function receives.

interactive decides whether this cell can be changed. Input boxes need not write it; they are editable by default. The result box is already non-editable in Interface — you cannot click into it or type in it. The interactive: false written in the sample only makes this fact explicit; it is not the reason it takes effect. To actually make an output editable you have to write interactive: true explicitly, which Chapter 3 will use.

Why is the result box disabled? Because it displays the handler function’s return value, not an input. Let people edit it and the edited content is not sent back, it is overwritten on the next run, and it only makes them think the edit took effect. Every output component that “only displays” should have interaction turned off.

As for what type Textbox passes to the handler function, this chapter gives the answer up front: string. It has other forms too (password box, length limit, submit on Enter), covered one by one in Chapter 6. How the component’s parameters match the handler function’s parameter types, and what happens when they do not, is treated systematically in Chapter 3.

Besides label, there is one more name worth getting right while you are at it: the handler function’s parameter names. They do not appear on the UI, but they do appear in the interface documentation. In this chapter’s /gradio_api/info, the parameter_name of the two parameters are text and separator, matching Split’s parameter names. What people see is label; what callers see is the parameter name — do not use names like a or b in either place.

The order of decisions is: first fix the types of the inputs and outputs, then fix the number and order of the components, and only then tune the components’ detailed parameters. Reverse that order and you will spend your time tuning a component you chose wrong.

2.3 Initial Values and Examples

Initial values were covered in the previous section. Whatever you put in value is what is in the box when the page opens. It takes effect only at that one moment.

examples are ready-made inputs prepared for the user. The form is one group per row, with the values in each row arranged in the order of inputs, one value per input.

examples: new[]
{
    new[] { "apples, bananas, oranges", "," },
    new[] { "first;second;third", ";" },
},

Two examples render as a table on the UI, whose header is the components’ label (the block below Figure 2-2). The table has two rows and two columns; the first column is “Text to split”, the second is “Separator”.

Examples have two uses. One is convenience: the user does not have to think up what to type, picking a row gives ready-made values. The other is documentation: putting two examples there is tantamount to telling people what kind of input this tool accepts, and that the separator can be a comma or a semicolon. The second use is often underestimated. Once a tool is in other people’s hands, the person writing the instructions is usually you, and an examples table is less work than a paragraph of explanation and less likely to go out of date.

Click any cell in an example row.

Figure 2-4 After clicking the second example

Both input boxes change together. The text to split becomes “first;second;third”, the separator becomes “;” — exactly the values of those two cells in the second row. Columns and inputs line up by order. The first column goes to the first input, the second column to the second input, the same rule as “order is the contract” in 2.1. The examples table is not just decoration; one click fills in the form.

The result area does not move along with it. Examples do only one thing, “filling in values”; they do not click the button for you. What the result of that row is, you have to find out by clicking “Split” yourself. This is the same behavior as the initial values. Filling in values is one thing, running the function is another. Click the second row and then click “Split”, and the right side shows “first / second / third” plus a line “. 3 segments”, which matches the group you filled in by hand.

One more detail is easy to miss. You click one cell, but the whole row is filled in. That cell is only the entry point; the values are distributed to each input by column. And precisely because it fills the page rather than the configuration, pressing F5 to refresh returns both boxes to their initial values.

2.4 Submit, Stop, and Clear Buttons

There are places for three buttons on the UI. Clear is on the left, Submit on the right, and the stop button is normally invisible (Figure 2-2 shows only the first two).

submitBtn is the text on the submit button. Without it, it defaults to Submit; this chapter’s sample gives “Split” instead. The wording is worth choosing carefully: writing an action (Split, Clean up, Convert) is better than writing “Submit”. Users read the button text before they click, and a word that names an action reassures them more than a generic one does.

clearBtn is the clear button; its default text is Clear. It does two things: it clears all input boxes and it clears all output boxes. There is one point that is easy to misremember: clearing is not restoring the initial values. This chapter’s sample has initial values “apples, bananas, oranges” and “,”; click Clear and both boxes are empty, not back to those two rows of initial values. The initial values are used only once, when the page loads; clearing is just clearing.

There is one thing about clearBtn that is easy to misunderstand. Passing null means adopting the default Clear, so visible is still true. To change the text, give a string; to make it not show, pass ButtonSpec.None, and that button’s visible becomes false.

stopBtn is the stop button, drawn only when the handler function returns a stream. This chapter’s Split returns a single string all at once, not a stream, so even if you give stopBtn some text, no stop button appears on the page.

The stop button solves a different kind of problem: the handler function takes tens of seconds to run and the user wants to give up halfway. A function that returns all at once has no “halfway” to speak of; once clicked you can only wait for it to finish. So not having it now does not affect anything.

timeLimit is a parameter in the same direction. It sets a time limit for streaming runs, 30 seconds by default. This chapter’s handler function is not streaming, so changing this value makes no observable difference on the UI. Both the stop button and the time limit only become meaningful in Chapter 16, when streaming output is covered.

There is one more button that appears by default, Flag. It marks a particular input/output pair and stores it as a record. This chapter’s sample turns it off with flaggingMode: "never". This tool has no samples that need manual marking; leaving it there only invites misclicks. If you do not write this parameter, the page gets this extra button.

Of the three buttons, only submit is required. The stop button exists only when there is a stream; the clear button can be hidden — passing ButtonSpec.None keeps the button from being generated, and it is harmless to most tools anyway. Just do not expect it to restore the boxes to their initial values. The basis for the decision is still that old question: what does the person using it want to do next.

2.5 Launch Parameters and Port Conflicts

demo.Launch() has four parameters you can write, and this line writes none of them.

demo.Launch(
    serverName: "127.0.0.1",
    serverPort: 7860,
    preventThreadLock: false,
    quiet: false);

The values in the block above are exactly the defaults; they are written out only to make clear what is available. Of the four parameters, the first two decide “where to listen”, and the last two decide “how to wait” and “whether to speak”.

serverName defaults to 127.0.0.1, which means only the local machine can connect. Change it to another address and you expose the application on another network interface, so people on the same network segment can open it too. That is beyond the scope of this book; the three limitations in Chapter 1 make it clear that it is for personal use on the local machine only. So none of this book’s samples change it.

serverPort defaults to 7860, the port in the browser’s address. The preface covered how to change the port and how to troubleshoot when the port is occupied; here we only cover what you can see from the application’s side.

When the port is occupied, launch another instance of the same application and the second process outputs this:

System.IO.IOException: Failed to bind to address http://127.0.0.1:7860: address already in use.

Then the whole process exits, ending as an uncaught exception, with exit code -532462766 (that is, 0xE0434352 in hexadecimal, the fixed code for an unhandled exception in a .NET process). The first application is unaffected and keeps serving normally.

Let us break this behavior down.

It does not switch ports automatically. If the port is taken, startup fails; it does not fall back and try 7861, 7862, and so on. This is a good thing. The address is something the user keeps in a bookmark; silently changing it is worse than failing.

It does not just warn and keep running. Failure is failure: the process exits and the page cannot open. So when you see the browser cannot connect, the first thing to do is check the console, not refresh the page.

It affects only the new process. The old one is still there, holding the port and continuing to serve. This also explains the most common scenario: you forgot to close the application from your last run, so the new startup fails, the UI still shows the old one, and the new code never ran even once.

What holds 7860 is usually an instance from your last run that you did not close, or a debug session still hanging in the IDE. The preface gives troubleshooting steps for who is holding it and whether to touch it, so they are not repeated here.

One habit that saves a lot of time: run only one instance at a time, and when startup fails, look at the first line of the console rather than refreshing the browser first. The browser only tells you it cannot connect; the console tells you why.

quiet defaults to false: on startup it prints that one line with the address, plus a few lines of ASP.NET startup logs. Set it to true and the console shows not a single word. It does not just turn off the address line; the startup logs go too, and the output file is 0 bytes. So it suits the case where “you know it is running and do not want to see logs”, not first-time debugging. When something goes wrong, you cannot even tell whether it came up.

preventThreadLock defaults to false, meaning Launch blocks until the process is stopped (Ctrl+C). Set it to true and Launch returns a server object immediately, and the code after it keeps going. There is one thing to know first. The service runs inside this process; once the program ends, the service ends with it. So it suits being hosted by another host. In that scenario the process is managed by another layer’s lifecycle, which Chapter 21 will use; written as the last line of top-level statements it is meaningless.

There is also an implicit convention: one listening address per process. To run two applications at the same time you need two processes and two ports.

2.6 Where Interface Applies

Interface fixes the layout: inputs on the left, outputs on the right, a row of buttons below, and the examples table below that. You cannot change this structure; all you can change is the content, the text, and a few switches.

This structure maps to one model: fill in a form, submit, see the result. One loop, run once, done.

This model covers more scenarios than you might think. This chapter’s splitting is one; Chapter 1’s text cleanup is one; formatting a piece of JSON, computing a summary over a batch of data, or resizing an image are all examples. What they share is one operation, one result, and inputs and outputs that all fit on one screen.

Cases outside the boundary are easy to recognize too. If any of the following appears, Interface cannot express it.

If one page needs to hold two unrelated operations, Interface cannot lay them out. It has only one submit button and can run only one function at a time.

If you need to save the previous result so that two operations are related, there is no place to store it here.

If you need sections, collapsing, pagination, or two operations triggering each other, Interface does not even have the vocabulary to express these.

These belong respectively to Blocks in Chapter 4, events in Chapter 5, state in Chapter 14, and layout in Chapter 18.

But that does not make this chapter a transitional one. The value of Interface is that it lays out three things most clearly: which component feeds which parameter, which return value lands in which component, and what happens when the button is clicked. These three still hold under a different way of organizing things, only then you have to write them out yourself. Understand them first, then look at freer layouts, and you will not mix “UI” and “logic” together.

The dividing line falls on the number of loops. With only one loop, Interface’s three elements match up one to one; when a second loop appears, or two loops need to affect each other, it is time to switch to Blocks. It has only one submit button and cannot store the previous result either.

2.7 Chapter Summary

The three elements of Interface are inputs, function, and outputs. The components in inputs become the handler function’s parameters in order, and the components in outputs receive the return values in order. A wrong order does not report an error, it only computes wrong, so treat the order as a contract to remember.

Initial values are only filled into the input boxes; they do not automatically run once when the page opens. Clicking an example row fills that row’s values into each input box by column, and does not run the function either. What examples save is typing, not clicking the button.

Of the three buttons, only submit is required. The stop button appears only for streaming handler functions, and the clear button clears inputs and outputs together without returning to the initial values.

Launch has four parameters: listening address, port, whether to return immediately, and whether to be quiet. When the port is occupied it reports an error and exits; it does not switch ports automatically, nor does it just warn and keep running.

Interface fits the single “fill in a form, submit, see the result” loop. When a second loop appears, it is time to switch to a different way of organizing things.

The next chapter covers the contract between components and handler functions: what type a component passes to the handler function, what the handler function should accept and return, and what happens when they do not match.

Chapter 3. Component Contracts and Handler Functions

The application in Chapter 2 runs because the two sides happen to line up, yet nothing in the code guarantees it. Split takes two strings, and inputs holds two Textboxes. The count and the types are hard-coded separately, with no check in between.

Switch to three inputs, or make one of them a number, and it no longer necessarily holds. What type a component passes to the handler function, which component a return value is written into, and what happens when the counts don’t match. These are the contracts this chapter makes clear. Once the contracts are clear, you can write the signature straight from a requirement, without trial and error.

This chapter’s example is a line-wrapping tool. A piece of text, a character count per line, and a switch; it outputs the wrapped Body, the Statistics, and the Notice. The business rules live in a class library that does not reference Gradio.NET, and the UI project is responsible only for components and type conversion.

3.1 Component Factories and value

First look at the code on the UI layer.

using Chapter03.Core;
using Gradio.Net;

const string SampleText = """
Wrapping looks simple,
but first settle a few small rules.
Trim each line ending,
Skip all blank lines
Then count lines and characters.
""";

var source = gr.Textbox(label: "Source text", value: SampleText, lines: 8);
var width = gr.Number(label: "Characters per line", value: 30);
var keepEdits = gr.Checkbox(label: "Keep my edited body", value: false);

var body = gr.Textbox(label: "Body", lines: 12, interactive: true);
var stats = gr.Textbox(label: "Statistics", lines: 2, interactive: false);
var notice = gr.Textbox(label: "Notice", lines: 3, interactive: false);

(object, string, object) Layout(string text, double? width, bool keepEdits)
{
    var result = TextLayout.Wrap(text, width);

    var report = result.Report;

    object bodyValue = keepEdits ? gr.Skip() : result.Text;

    var statsValue = $"{report.Lines} lines, {report.Characters} characters, longest line {report.LongestLine} characters";

    object noticeValue = report.Warnings.Count == 0
        ? "No issues to report"
        : gr.Update() with
        {
            Label = $"Notice ({report.Warnings.Count} items)",
            Value = string.Join("\n", report.Warnings),
        };

    return (bodyValue, statsValue, noticeValue);
}

var demo = gr.Interface(
    Layout,
    inputs: [source, width, keepEdits],
    outputs: [body, stats, notice],
    title: "Line Wrapping and Cleanup",
    description: "Wrap a piece of text by the character count per line, and also report the line count, the character count, and the longest line.",
    submitBtn: "Clean up",
    flaggingMode: "never",
    apiName: "layout");

demo.Launch();

Calls like gr.Textbox(...), gr.Number(...) and gr.Checkbox(...) are called component factories. Write one, get one component object; all the arguments are named and can be omitted. You can build one without writing any, like gr.Textbox(), and an empty box with no label appears on the page. It works, but nobody knows what to fill in. That is what label is for.

The six component objects go into variables first, then into inputs and outputs. This step is not required; you can also write inputs: [gr.Textbox(...), gr.Number(...)], putting the factory calls straight into the collection. The only benefit of writing them as variables is that it reads clearly. Who sits in which position can be matched at a glance across the two list lines.

A component object is a declaration, and also an object you can reference again.

It is a declaration because it tells the framework “there is an input box here on the page, labeled Source text, taking 8 lines”. Its position in inputs decides which input it is; its position in outputs decides which output it is.

Here we need to be clear about what a component object is. Writing gr.Textbox(...) produces a description: what the type is, what the label is, how many lines it takes, what the initial value is. The real input box is drawn by the browser from that description. So “using the same component object twice” is “asking for the same description to be drawn twice”. The framework rejects the latter, because a description and a position on the page are one-to-one.

value is a property of a component, but it has two identities. At construction time it is the initial value, the content pre-filled in the box when the page opens. Once running it is the current value: when the user changes it, it changes along; when the handler function returns a new value, it is replaced. So value is “the value this component holds at this moment”. It just happens that you can supply one at construction time. Chapter 2 said the initial value does not trigger a run when the page opens — that was about triggering; the value itself has always been this value.

A component object can go in only once. Put the same Textbox into inputs twice and constructing Interface throws an exception.

System.InvalidOperationException: 'Textbox' is not waiting to be rendered by this application;
it was never added here, belongs to another render root, or has already been rendered.

The meaning is simple. A component has only one position on the page; once rendered, it is gone. If you want two input boxes that look the same, create two component objects; if you want two inputs to share one configuration, extract a method that builds one each time, rather than stuffing the same object in twice.

One more thing: components in outputs are generally non-editable by default. This chapter’s body writes interactive: true, and that is what makes it editable by hand; stats and notice don’t write true, so they are grayed out.

Why are outputs read-only by default? Because they show the result of the handler function, not an input. Let people edit them and the edited content is not sent back, and it is overwritten again on the next run. This chapter’s body is an exception. This tool is used by “first wrapping automatically, then fixing a few lines by hand”, so it needs to be editable, and the “Keep my edited body” switch is there so the next run does not wipe out the manual edits. The Skip part is covered in 3.4.

Launch the example and the UI looks like this.

Figure 3-1 The initial UI of the example

Three inputs on the left, three outputs on the right, and a “Clean up” button in the middle. Source text already has an initial value, and all three outputs are empty. As in Chapter 2, opening the page does not run once.

3.2 Handler Function Parameters and Component Data Types

Layout’s signature is the core of this chapter.

(object, string, object) Layout(string text, double? width, bool keepEdits)

The three parameters correspond to the Textbox, Number and Checkbox in inputs, exactly one each.

The component decides the type; the handler function can only accept what it is given. The correspondence is listed in this table.

ComponentParameter type passed to the handler functionNotes
TextboxstringAn empty string when blank, not null
NumberdoubleCan be declared as int, decimal, double?; the framework converts according to the declaration
SliderdoubleSame as above
CheckboxboolOnly two possible values
DropdownstringA single value for single-select; the multi-select form is covered in Chapter 7

The Number row needs expanding. What the component itself passes to the handler function is a double. A number comes from the browser as a number in JSON and is read into C# as a double-precision floating-point value. You can declare the parameter as int or decimal and the framework converts once more according to your declaration; if it cannot convert, it reports an error rather than silently truncating. The example declares it as double? to tell “not filled in” apart from “filled with 0”. More on this in 3.5.

The declared type has to hold the value the component gives. A Textbox’s string fits into string and object; a Number’s double fits into double, float, int, long, decimal, double? and object; a Checkbox’s bool fits only into bool and object. The reverse does not fit. Stuff a Textbox’s string into an int and you get an exception. object always fits, so it is the most convenient while debugging and the least useful in everyday code, because the compiler can no longer help you.

Which numeric type to declare depends on whether you want decimals and whether you want precision. Use int for counts, double for ordinary measurements, and decimal for values like amounts of money that cannot have binary error. Number converts once according to the type you declared; if it cannot convert, it reports an error and does not round for you.

Parameters correspond by position. Layout’s first parameter is called text only because it sits first and corresponds to the first component in inputs; rename the parameter to content and everything stays the same. But the name is not entirely useless: it appears in the interface documentation. In this chapter’s /gradio_api/info, the parameter_name of the three parameters are text, width and keepEdits. What people see is label; what callers see is the parameter name.

That interface documentation can also answer “what does the framework think this component is”. In the same response, every parameter carries its type and component, {"type": {"type": "string"}, "component": "Textbox"}. When the signature is wrong and the UI shows only “Error”, look here first. It tells you which type the framework has computed for which component, which is faster than guessing in the code.

How do you know what type the component you wrote actually passes? You can wait until Chapter 6, when the components are covered one by one, and note them down; or temporarily write the parameters as object and print their runtime types inside the function.

static string Probe(object? a, object? b, object? c)
    => $"{(a?.GetType().Name ?? "null")} / {(b?.GetType().Name ?? "null")} / {(c?.GetType().Name ?? "null")}";

Return values have to be caught too. Output components have their own types as well; the rule is the same as on the input side, only the direction is reversed, and a component can only display values of its own kind. Textbox accepts strings, Checkbox accepts true/false, Dropdown accepts one of its options; give Number a string and it throws at runtime

System.ArgumentException: A number field's value is a number; the handler returned a System.String.

The input types are decided by the components, the output types are decided by the components, and the handler function sits in between, so the types on both ends must match. Once they match, the code in the middle is just ordinary C#. Not one line in this chapter’s Layout deals with type conversion; the conversion is all done on the component side.

3.3 inputs, outputs, and Multiple Return Values

Three inputs, three outputs, and the handler function returns a three-tuple. The correspondence is simply one-to-one in order.

Figure 3-2 Three inputs become three parameters, and three return values land back in the three outputs

Launch the example and click “Clean up”.

Figure 3-3 After clicking “Clean up”

The Body is wrapped to 30 characters per line, Statistics reports “7 lines, 109 characters, longest line 30 characters”, and Notice says “No issues to report”. The three return values each land in their own place, in the right order.

Inputs and outputs need not be equal in number. One input feeding three outputs is common, and three inputs feeding one output works too; there is no constraint on count, only on order.

A wrong position does not report an error either, it just computes wrong. Swap the order of the three output components in outputs and statistics text appears in the Body’s place. The types are all string, so any of them can accept it, and the UI just “looks a bit off”. This kind of error can be avoided by one thing only: the order of outputs and the order of the handler function’s returns are the same sentence in your head.

If you really suspect you got the order wrong, there is a clumsy but effective method. Have the handler function return three obvious markers, like ("one", "two", "three"), run once, and see which word appears in which box. It is faster than staring at the code and more reliable than guessing.

A tuple can also carry names, like (string Body, string Stats, object Notice). Names do not affect the correspondence; they just make the returned line read like a sentence. The example does not name them because it already splits them into variables in the function body; when one of your functions returns four or five values, names become useful.

Back to the example’s return type (object, string, object). Why are the first and third object? Because those two positions may hold something that is not a string. The first may be the update returned by gr.Skip(), and the third may be an Update. When one position has to hold two kinds of things, you can only fall back to their common parent type. The second position is always a string, so it honestly says string.

This chapter needs object in only this one place, and only in the either-or position of “value or update”. Do not carry this habit elsewhere; write a concrete type wherever you can.

3.4 Contract Differences Between Return Values, Update, and Skip

The three return values of Layout each handle one thing. The following is a sketch; ... is detail left out, and the full code is in 3.1.

object bodyValue = keepEdits ? gr.Skip() : result.Text;
var statsValue = $"...";                       // a string
object noticeValue = report.Warnings.Count == 0
    ? "No issues to report"                     // a string
    : gr.Update() with { Label = ..., Value = ... };   // an Update

An output can be filled by three kinds of things: a value, an Update, or Skip.

A value is a replacement. stats is replaced wholesale every time, and no trace of the old statistics remains.

Update is “change only the named properties”. notice normally returns a string, and returns an Update when there are warnings, with only Label and Value written. The label becomes “Notice (1 item)”, and the content is replaced with the warnings. The other properties (height, whether editable, visibility) are all untouched, because they were not written.

Skip is “don’t touch it this time”. body returns gr.Skip() after “Keep my edited body” is checked. The Body stays as it is, while Statistics and Notice update as usual.

Figure 3-4 Clean up after checking “Keep my edited body”

In Figure 3-4, the Body is “This line is one I edited myself”, but Statistics has already become “5 lines, 109 characters, longest line 35 characters”. The statistics were recomputed at 60 characters per line, yet the Body was not overwritten. In a single run, some outputs are skipped and others replaced, each going its own way.

Update carries only the properties it wrote, and there is finer evidence of this on the UI. Fill in 5 for the characters per line and click “Clean up” once more.

Figure 3-5 Enter 5 for the line width and the Notice label becomes “Notice (1 item)”

The Notice’s label changed, its value changed, and the Body and Statistics updated as usual. This time the Update wrote two items, so only those two moved on the UI; height, whether editable, and visibility all stay as they were.

To verify “an item you didn’t write won’t change”, change one line. Delete the Label line in the example’s gr.Update() with, rebuild, and click once more. The label stays as it was (if it has not been changed yet, that is “Notice”), and the value is still replaced with the new one, because this time the Update wrote only Value and the client merges only that one item.

That is the whole difference between Update and “returning a value”. A value replaces the entire displayed content of the component; Update merges only the few items you wrote out.

Update can change quite a few properties; these are the common ones.

PropertyWhat it changes
ValueThe value the component holds
LabelThe label above the component
VisibleWhether it is shown or hidden
InteractiveWhether it can be edited
PlaceholderThe hint text in an empty box
InfoThe description below the component

The remaining properties (options, numeric range, size) are covered when their components come up; Update has an item of the same name for each. Properties not listed in Update fall back to Props, which accepts any property by its name in the configuration. This escape hatch is reserved for properties not yet modeled; you do not need it day to day, but when you meet a property that “exists in the component properties but not in Update”, you can use it.

How to choose? See whether this output has “something to preserve”. Statistics is a brand-new piece of text every time, and the old value has no worth keeping, so returning a value directly is the least trouble. Notice is different. Its label has to follow the content, while the label is normally “Notice” and is “Notice (2 items)” when there are warnings. The value changes every time, and the label sometimes changes and sometimes does not. Writing it with Update expresses exactly “which items changed this time”; writing it with a return value means computing the label every time too, and one wrong write leaves the label unable to go back.

One step further. If you do not even want to change the value and only want an output to stay as it is, that is Skip. This chapter’s body is exactly that case. The user may have fixed a few lines by hand, and the handler function has no right to overwrite it.

The three return styles correspond to three intentions: redo everything, change only a few items, change not a single item. Choosing wrong does not report an error; it only makes changes appear on the UI that you did not intend.

Value has one special value, Update.Clear. It means “write this item as null”. Leaving a property blank means “don’t touch”, and Value = null also means “don’t touch”, so to clear an output you must write Value = Update.Clear explicitly. This difference does not show up in the “replace everything at once” style of Chapter 2; you only meet it when using Update.

Skip is really “an Update with nothing written in it”. The object returned by gr.Skip() is the same thing as gr.Update(); when the framework sends it to the browser, it looks like this.

{"__type__": "update"}

An empty update, merged by the client, amounts to no merge at all. So Skip is a degenerate case of Update. This also explains why using it on one output while the others update as usual is not a contradiction.

There is one more, used less often: returning the component itself. Return the body object directly and the client receives all the properties from when the component was constructed. Value, label, line count, whether editable — all reset to their factory state at once. It suits operations like “restore defaults”: for example, a “Reset” button restores all the outputs to how they looked when just opened, and the handler function returns the component objects one by one without having to copy every default value again. It does not suit everyday updates. You want to change one value, but you also knock the label and editability back.

The four styles divide by purpose: return a value by default; use Update to change only appearance; use Skip when you do not want to overwrite someone else’s work; return the component itself only to get back to the initial state.

3.5 Empty Values and Type Boundaries

An input box is cleared; what does the handler function receive?

A text box gives the empty string "", not null. A number box gives null. These two differences are not small. string text will never become null because of “not filled in”, while double? width will become null because it was not filled in.

This chapter’s example works precisely because of this. width is declared as double?; after the number box is cleared it is null, TextLayout.Wrap recognizes “not filled in”, handles it with the default 30, and gives a warning.

Characters per line not filled in, using 30

What if it is declared as double (without the question mark)? null is converted to 0, with no error. TextLayout.Wrap receives 0, clamps it to the minimum 10 by its rules, and so you get a Body wrapped at 10 characters per line and a warning “at least 10 characters per line”. That 0 came out of null; the user filled in nothing.

This is a quiet error, more troublesome than throwing an exception. An exception at least stops; this one keeps running and even gives you an output that looks reasonable. The rule is simple. For any parameter where “not filled in” and “a value was filled in” need to be treated differently, declare it as a nullable type. This applies to numbers, booleans and dates; strings do not need it, because the empty string already means “not filled in”. Unless the empty string itself has meaning in your business logic, in which case you need a different marker.

The return side has empty values too. Returning null to an output component clears it. In 3.3, when one fewer value is returned, that position receives null, and the UI shows that cell empty. So “clear an output” has two ways of writing it. Return null, or return an Update with Value = Update.Clear. The former replaces the whole component with an empty value along the way; the latter changes only the value and leaves the other properties alone. Use the latter when you need to keep the label and height.

Finally, type boundaries. You saw two kinds of failure earlier: the input type cannot hold it, and the return type cannot hold it. What they share is that you cannot see them at compile time; at runtime the server throws an exception, and the UI shows only “Error”.

This feedback is weak, so spend ten extra seconds when writing. Check every type in the signature against the table in 3.2; check the return types against every component in outputs once more. After these two passes, that runtime failure can basically be avoided.

There is one boundary that is not about type but about count. With too few inputs, the missing parameters get their type’s default value — string is null, int is 0; with too many inputs, the extra ones are ignored. These two, like the return side, do not report an error either. So “three inputs, three parameters” is something you have to check for yourself too.

There is a very practical diagnostic for this situation. When some parameter is mysteriously null inside the function, first count how many components are in inputs and how many non-injected parameters are in the signature. Once you have counted, you will most likely have found it. Either one component too few was placed, or one parameter too many was written.

The last thing is about where to put these boundaries. This chapter’s TextLayout.Wrap never throws an exception. When the text is empty, it returns an empty result plus a warning; when the line width is out of range, it clamps to the valid range and adds a warning; when there are too many lines, it truncates and adds a warning. All the “not ideal but can continue” cases become one line in LayoutReport.Warnings, and the UI decides how to display it.

The benefit of this is that the boundary exists in only one place. The UI layer does only two things. It hands the components’ values to the business logic, and it puts the business result back into the components. It does not judge “whether the text is empty”, nor “whether the line width is valid”. Those judgments are all in core, traveling with the business rules. If one day you want to run the same set of rules on the console, this whole UI layer can be dropped as a block, and what remains still works.

This chapter’s example is split into two projects. core/Core.csproj does not reference Gradio.NET and has no idea what a Textbox is; Chapter03.csproj references core and handles only components, types, and the three return styles. The boundary between the two projects is the boundary between “business” and “UI”.

3.6 Chapter Summary

A component factory writes once and produces one component object, which is both a position on the page and an object you can reference again later. This chapter needs that second reference only in “returning the component itself” in 3.4. value is the value it holds at this moment, and the one given at construction time is the initial value. A component object can go in only once, and output components are non-editable by default.

The component decides the type. Textbox gives string, Number gives double (can be declared as int, decimal or double?), Checkbox gives bool. Parameters correspond by position; if they cannot hold the value it fails at runtime, the UI shows only “Error”, and the reason is in the console.

Multiple return values land in multiple outputs in order. With too few, the missing positions are cleared; with too many, the extras are dropped; neither reports an error, so write the return type as a tuple whenever possible and let the compiler count for you.

An output can be filled by three kinds of things: a value, Update, Skip. A value replaces, Update merges only the named properties, and Skip is an empty Update. Returning the component itself is a fourth, used for resets. To clear a value, use Update.Clear and do not count on null.

An empty text box gives "", an empty number box gives null; if you do not want “not filled in” mixed up with 0, declare the parameter as a nullable type.

The next chapter switches to a different way of organizing things. No longer one function plus a set of inputs and outputs, but several areas laid out on one page.

Chapter 4. Blocks and Layout Containers

The line-wrapping tool in Chapter 3 has only one action in its UI: fill in three boxes, click once, and see three results. You can build this kind of UI with Interface in a few lines, because it has only one column of inputs and one column of outputs.

The workbench is different. It needs a title, an area that collects inputs, an area that holds results, and later tables, files, and chat. These areas exist at the same time; they are not sequential. Interface cannot express this — its layout is fixed: inputs on the left, outputs on the right, the button in the middle.

Blocks can. With it, you no longer describe “how a function becomes a UI”; you describe “what a page looks like”. Which areas are on the page, which components are in each area, and what sits inside what.

This chapter builds the single-page skeleton of the workbench. When it’s done, the page is divided into three areas with a clear structure, but the buttons don’t respond yet. Events are a topic for Chapter 5. This chapter’s UI is static.

4.1 From a Single Operation to Multiple Interaction Areas

Interface’s model is “one operation”. It assumes the user opens the page, fills in a few values, clicks a button, sees a few results, and closes it. The app in Chapter 2 and the line-wrapping tool in Chapter 3 both fit this model. One operation, one result, inputs and outputs each taking one column — Interface’s fixed layout lines up exactly.

The workbench doesn’t fit. It is “several things on one page”. Text cleanup is one, table checking is another, file handling is a third. Users come in looking for entry points to work, not to perform one particular operation. Interface can’t hold this kind of UI.

First, the areas are side by side. The title belongs neither to inputs nor to outputs; the result area takes no parameters, it only displays things. Interface cuts the page into two piles, “inputs” and “outputs”, with no place to put something that “belongs to neither pile”.

Second, the areas have a containment relationship. The Body, Statistics, and Notice in the result area form one group and should be drawn inside one frame; the three fields in the input area are another group. In Interface all inputs are laid out flat in a single column, so you can’t separate groups.

Third, the areas keep growing. Chapter 5 adds buttons to the input area, Chapter 9 adds a table, Chapter 13 adds a chat. Every addition has to find a spot outside those two columns, and Interface has no third spot.

Blocks’s model is “one page”. You write the nesting relationship between containers and components; what the page looks like depends on how you nest them. It doesn’t presuppose how many areas the page has, or who is on the left.

The skeleton this chapter builds looks like this.

  • A top strip: a title and one line of description;
  • A middle block: inputs on the left (source text, characters per line, keep edits, plus a button), results on the right (body, statistics, notice);
  • A bottom block: advanced options, hidden by default.

Three areas, two directions, one corner that doesn’t appear by default. Together, these use every container this chapter covers.

Why spend a whole chapter just placing the skeleton? Because every later chapter adds to this skeleton. Chapter 5 adds events, Chapters 6 to 13 each add a module, and Chapter 18 splits it into multiple pages. Place the skeleton wrong and every later chapter has to be reworked; place it right and adding a module is just “writing a few more lines inside some using”.

The sample is in samples-en/chapter04, with two projects. core holds the line-wrapping and statistics rules and does not reference Gradio.NET; Chapter04.csproj only handles the page. At the skeleton stage there are no events yet, so the result area first gets a sample computed at startup. Run core once and fill in the result. That way the page isn’t empty, and you can see how much space each area takes and whether things get cramped with a lot of text. This sample is replaced by real results only when Chapter 5 wires up the buttons.

After you launch it, you’ll find the “Clean up” button does nothing when clicked. That’s this chapter’s state, not a defect. The first thing Chapter 5 does is bind an event to it.

This chapter’s scope is clearly drawn too. Event binding is left to Chapter 5; the collapsing and paging containers like Tabs, Accordion, and Sidebar are left to Chapter 18; themes and CSS are left to Chapter 19. This chapter uses only four containers, to lay the page out into something usable.

4.2 Blocks and the Component Build Context

First, look at how this page is put together.

var demo = gr.Blocks(title: "Personal Local Workbench");

using (demo)
{
    // Title area: only a title and one line of description, taking up a full row.
    using (gr.Column())
    {
        gr.Markdown("# Personal Local Workbench");
        gr.Markdown("A piece of text, a table, and a few files are all handled on this one page.");
    }

    // Main area: inputs on the left, results on the right.
    using (gr.Row())
    {
        using (gr.Column(scale: 2, minWidth: 480))
        {
            gr.Markdown("### Text Cleanup");

            gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
            gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
            gr.Checkbox(label: "Keep my edited body", value: false);

            gr.Button("Clean up", variant: "primary");
        }

        using (gr.Column(scale: 1, minWidth: 320))
        {
            using (gr.Group())
            {
                gr.Markdown("### Result");
                gr.Textbox(label: "Body", lines: 12, value: preview.Text, interactive: true);
                gr.Textbox(label: "Statistics", lines: 2, value: Stats(preview.Report), interactive: false);
                gr.Textbox(label: "Notice", lines: 2, value: Notice(preview.Report), interactive: false);
            }
        }
    }

    // Advanced area: hidden by default, invisible on the page, and leaves no empty space.
    using (gr.Row(visible: false))
    {
        gr.Markdown("### Advanced options");
        gr.Textbox(label: "Separator", value: ",", info: "What separates multiple values");
        gr.Number(label: "Line limit", value: 200);
    }
}

demo.Launch();

This code rests on one premise that runs through the whole chapter. A component belongs to the innermost open container.

Look at the first line. The title in gr.Blocks(title: "Personal Local Workbench") is the name on the browser tab and the value of the title field in /config. It has nothing to do with the # Personal Local Workbench on the page. The latter is a Markdown component — it shows whatever you write — and the two can differ.

gr.Blocks(...) creates the root container. using (demo) opens it, and everything inside the braces is placed on the root. using (gr.Row()) opens another layer inside, so components in that layer land on the Row. Go further in with using (gr.Column(...)) and components land on the Column. When a brace ends, that layer closes and later components go back to the previous layer.

Figure 4-1 Components land in the innermost open container

Figure 4-1 shows three moments. Just after entering Blocks, the top of the stack is the root, so components land directly on the root. After entering Row, the top is the Row, so components land in the Row. Enter Column and the top is the Column, so components land in the Column. That’s why gr.Markdown("### Text Cleanup") appears in the input area — it’s written inside that Column’s braces.

There’s an easy-to-miss detail here. A container is pushed onto the stack as soon as it’s created; using only pops it off when the braces end. So if you “don’t write using”, that layer stays open.

using (demo)
{
    var input = gr.Column();      // pushed onto the stack, no matching pop
    gr.Textbox(label: "Source text");     // lands in Column
    gr.Textbox(label: "Statistics");     // also lands in Column
    gr.Button("Clean up");            // still lands in Column
}

All three components above are in the input column; none went back to the root. To verify, create another Row after the Column and you’ll find the Row has also become a child of the Column, because the top of the stack is still the Column. This mistake throws no error — the page still renders — only everything is crammed into the same area.

Containers must close in nesting order: using the outer layer first, then the inner, and in reverse when exiting. Closing in reverse (outer first, then inner) doesn’t throw an exception, but later components land in a container you didn’t intend. This kind of problem is hard to spot by reading the code; on the page the component positions are simply misplaced.

There’s a third way of writing it, harder to track down than the two above.

var outside = gr.Textbox(label: "Created first");   // written before using (demo)

No error, no warning, and the box isn’t on the page. Its Parent is null and its Id is -1, meaning “it was never added to any page”. The component object is still a valid object; nobody just holds it. So for the question “I clearly wrote this textbox, why isn’t it on the page?”, the first thing to check is which layer of braces it was written in.

The three ways of getting the position wrong have different symptoms and different ways to find them.

Way of writingError?SymptomHow to find it
Container without usingNoAll later components crammed into one areaLook at the page, one area is missing
Component outside all using blocksNoThe component is not on the pageId is -1, Parent is null
Braces out of orderNoComponents land in an adjacent areaLook at the layout tree in /config

The /config mentioned in the third row is another way to check. After launching the sample, open http://127.0.0.1:7860/config; it has a layout field, which is the container tree for the whole page. The indentation in your code should correspond one-to-one with this tree: indent one level more in the code and the tree gains a level. If they don’t match, the braces are wrong. The later sections on containers keep coming back to this tree. It’s more precise than the page: the page only tells you “it looks off”, the tree tells you “where it’s off”.

Sealing

The page can’t be changed forever. Blocks has a “sealed” state; once sealed, adding components to it is rejected.

System.InvalidOperationException: This application is already being served, so it no longer
accepts blocks: the page a browser sees is the one written before the host started. Write the
UI before starting the host — the host seals the application when the first request arrives.

This error means the application is already being served, and the page is the one written before the host started; the UI must be finished before starting the host, and the host seals the application when the first request arrives.

When do you run into it? The most direct case: you call demo.Seal() before the page code is finished, then add components. The exception is thrown right there. The second is more common: putting demo.Launch() in the middle of the page code. Normally the process just stops there, the code after it never runs, and you see no error at all — only none of those components appear.

The timing of Seal is this: after Launch but before the page is visited, IsSealed is False; after the browser opens it once, it becomes True. So the exact order is, finish the UI first, then Launch. This has no exceptions and no need for a workaround. The point of Seal is to stop someone from changing the structure after the page has already been sent out.

One more thing: in everyday app writing you don’t need to call Seal manually. It’s used by the framework itself, and it’s what enforces “the UI must be finished before Launch”.

4.3 The Division of Labor Among Row, Column, and Group

Four containers, each with its own job.

ContainerDirectionWhat it managesTypical use
RowHorizontalPlaces children side by side, splitting width by scaleInputs left, results right; a row of buttons
ColumnVerticalStacks children top to bottom, each its own blockVertical arrangement inside one area
GroupVerticalJoins children into one block sharing an outer frameA group of results, a group of related fields
FormVerticalGenerated automatically by the framework, wrapping consecutive form componentsDon’t write it, see 4.4

Row and Column are layout directions; Group is “visually one whole”. The difference among the three is visible on the page.

In a Column each child is its own block, with a 16-pixel gap between blocks; in a Group the children share one outer frame with nothing separating them. This chapter’s result area uses Group. The Body, Statistics, and Notice boxes sit together and look like one “result panel” rather than three unrelated things. The input area uses Column. The three fields each take a row and are separated, because they were never one whole.

Figure 4-2 The skeleton’s structure tree, containers nested in containers, dashed boxes added by the framework

Figure 4-2 is the skeleton’s actual structure, read from the layout in /config and drawn as a tree. It’s simple to read: indentation means containment, blue is a layout node, black is a component, and the orange dashed boxes are groupings the framework added (covered in 4.4).

Look at a few positions.

  • The topmost column holds the title and one line of description; it isn’t side by side with anything;
  • Under the row are the two main columns: the scale=2 column holds the inputs, the scale=1 column holds the results;
  • In the result column there’s first a group, and inside the group are the title and three output boxes;
  • The last row is marked visible=false — the advanced area hidden by default.

There’s no limit on nesting depth. You can put a Column in a Row and a Row in that Column, as long as every layer opens a using. But as the layers grow, the code’s indentation is the first to suffer. This chapter’s skeleton goes at most four levels deep (Row → Column → Group → component); deeper than that and you should think about splitting it.

How to split? Write “one area” as a method and call it inside the using.

using (demo)
{
    Header();
    TextModule();
    ResultPanel();
    Advanced();
}

void TextModule()
{
    using (gr.Column(scale: 2, minWidth: 480))
    {
        gr.Markdown("### Text Cleanup");
        gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
        gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
        gr.Checkbox(label: "Keep my edited body", value: false);
        gr.Button("Clean up", variant: "primary");
    }
}

Written this way, the indentation is always only two levels, and each area can be read and changed on its own. Mechanically nothing changes. The methods are called inside using (demo), and when called the root container is open, so the components built in the methods still land on the root. This chapter’s sample doesn’t split things up, because the whole point here is to see the nesting clearly.

A Row can hold more than three areas, with scale dividing by shares. Three columns at 3:2:1 with an available width of 1200 come out to 600, 400, 200. The more shares, the harder the ratio is to read — three columns is the practical limit; four or more usually means this screen is crammed with too much and you should consider splitting it with Tabs (Chapter 18).

You can also put a Row inside a Row. The most common use is “a row of buttons”. In a Column, the fields are on top and using (gr.Row()) holds two buttons side by side below. Here the buttons’ Row has no scale — it only handles horizontal placement and doesn’t take part in the outer width split; that’s the Column’s job.

How to choose between Group and Column? Look at whether this group of things “is one thing”. The three boxes in the result area are three facets of one thing, so use Group; the three fields in the input area are three different things, so use Column. There’s also a practical difference. Group removes internal gaps, so if you put fields that each need their own label inside, the labels end up very close together and cramped to read. Group is better for outputs, or for a set of short fields of the same kind.

Group differs from Row and Column in another way: it has no scale or minWidth parameters. That is, Group doesn’t take part in width splitting itself — how much it occupies is decided by the layer outside it; a Group placed in a Row is treated as one whole and gets one share. To make the result area take more width on a wide screen, you change the scale of the Column outside it, not the Group’s.

You can also put a Column or Row inside a Group. For example, if you want Body on the left and Statistics on the right in the result area, nest a Row with two Columns inside the Group. There’s no limit on combining containers; there’s only one criterion. Should this layer’s children sit side by side or stack up? Should they each be their own block or join into one block?

Launch the sample and the UI looks like this.

Figure 4-3 The skeleton’s initial UI: title area, input area, result area

Three areas, top to bottom. The title area fills a row; the main body is wide on the left and narrow on the right (2:1). The three fields in the input area each take a row with gaps between them; the three boxes in the result area sit together sharing one outer frame. That’s the difference between Column and Group — you can recognize it without looking at the code.

There’s one detail in the result area. “Body” has a white background and can be clicked into and edited; “Statistics” and “Notice” can’t. The interactive parameter decides this — more in 4.6.

4.4 Form and Automatic Grouping

In the table in the previous section, the Form row’s usage says “don’t write it”. But /config really does have form nodes — those are the three dashed boxes in Figure 4-2. Where do they come from?

At the end of rendering, the framework does one thing: it wraps consecutive form components into a form node. Form components are those that have a “value” and can be submitted — Textbox, Number, Checkbox, Dropdown, Slider, and so on. This chapter’s input area writes three of them.

gr.Markdown("### Text Cleanup");

gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
gr.Checkbox(label: "Keep my edited body", value: false);

gr.Button("Clean up", variant: "primary");

The three fields land in the same form, while Markdown and Button land outside it. You can see this wrapping directly in the layout of /config; the structure looks like this.

{"id": 15, "children": [{"id": 11}, {"id": 12}, {"id": 13}]}

15 is the automatically generated form; 11, 12, 13 are source text, characters per line, and keep edits. You didn’t write a single form in your code, yet it appears in the config.

When is the grouping broken? It breaks at a non-form component. Slip a line of description between two of those three fields in the input area and you get two forms instead of one; the same goes for Button — it doesn’t take part in grouping, so the “Clean up” button in the sample is outside the form. That’s the grouping rule: only form components go into a form.

This rule is also the only lever you have over grouping. To keep one group of fields separate from another, insert a Markdown between them. A small heading or a separating note both work; it becomes the break between the two groups. Conversely, to merge several items into one group, don’t put any non-form component between them — not even a single line of description.

Grouping doesn’t distinguish inputs from outputs. The three boxes in the result area (Body, Statistics, Notice) are also form components, so another form is generated inside the group. Even though “Statistics” and “Notice” are read-only and never meant to be filled in, this rule looks only at component type, not at what it does in this UI. Know this and you won’t be surprised by unexpected dashed boxes in the structure tree.

Grouping also affects width, and this is easier to get wrong than the grouping itself.

The form itself has no width; it’s the sum of the widths of the components it wraps. Each component counts as one share by default with minWidth 160, so a form with two fields carries scale 2 and minWidth 320. In a Column this has no effect — the column is vertical, width is set by the column, and the form gets scale 0, minWidth 0. But in a Row, the form does take part in the horizontal split.

The advanced area has exactly this structure: a Row with a Markdown heading and two fields. Right now it’s visible: false, so you can’t see it. Change that false to true, rebuild, and you’ll see a result that defies intuition. The heading isn’t on top; it sits side by side with the two fields, the heading taking 1 share and the fields 2 — at a 1280 viewport the heading is 400 wide and the fields 801.

The reason is the one above: Markdown itself takes 1 share, and the auto-generated form carries the two fields’ 2 shares. To get the heading on top, the correct way is to put the heading outside the Row, or wrap the two fields in a Column and put that into the Row.

So when you see oddities like “the heading went off to the side”, first count who at that level carries a scale. The auto-generated form is the one most easily forgotten — it isn’t in your code.

At this point one thing needs to be made clear, because it’s the most misunderstood point in this chapter. This form is not an HTML <form>.

There is no form tag on the page. In the browser that node is an ordinary div, just named form. So:

  • Pressing Enter in a field does nothing — no submit, no refresh, no button triggered;
  • To make a group of fields “submit together”, you rely on an event listing them all in inputs. That’s Chapter 5’s content;
  • form only decides where these items are drawn, how wide they are, and whether there are gaps between them.

The framework only handles automatic grouping; submission still requires you to write an event. These two things are often bundled together in other frameworks, but here they’re separate. UI structure belongs to containers, behavior belongs to events, each minding its own business.

4.5 scale, minWidth, and Area Ratios

The two main columns have different widths. Inputs go on the left, results on the right, and the inputs need more width. Two parameters decide this.

using (gr.Column(scale: 2, minWidth: 480))

scale is “how many shares”, not pixels. Left 2, right 1 means the available width is split into three shares and the left takes two. At a 1280 viewport, the page content is 1216 wide, 16 pixels are left between the two columns, and the remaining 1200 splits into three shares of 400 each — so 800 on the left, 400 on the right. The numbers line up; that’s all scale means.

The title area has only two lines of text and fits in one column, so there’s no ratio to divide. Whether to split into columns depends on the content. If you also want a row of action buttons to the right of the title, write a Row with two columns and set the ratio as needed. Splitting isn’t mandatory — one more container means one more level of indentation, and on narrow screens one more line wrap to think about.

Treating scale as pixels is the most common mistake in this section. Write scale: 800 thinking “I want 800 pixels wide”, and this column and the neighboring scale: 1 column become 800:1 — the neighbor is squeezed into a thin line. scale only understands shares, and only has meaning when compared within the same level and the same Row; comparing across levels is meaningless, because each level splits its own width.

minWidth is a different matter. Below this width, stop placing side by side and wrap. The left requires at least 480, the right at least 320; the two add up to 800, plus the 16-pixel gap makes 816. When the available width is less than 816, the two columns stack into one.

Figure 4-4 Viewport narrowed to 700 pixels, the two main columns stack into one

Figure 4-4 is the same page with the viewport narrowed to 700 pixels. The page content width becomes 576, and the two main columns stack vertically. Inputs on top, results below — the order is the order you wrote. The title area has nothing to change; it only ever had one column.

What this figure shows is that scale and minWidth are not the same thing; they govern two directions. scale governs “how to split when wide”, minWidth governs “when to stop placing side by side when narrow”. Write only scale and no minWidth and things get cramped on narrow screens; write only minWidth and no scale and the two columns are always equally wide on wide screens.

First, tell the defaults apart. A Column’s scale defaults to 1 and minWidth to 320, so two columns with no parameters are 1:1 and only stack below 656; a Row’s scale defaults to “not given” — in a Row it’s the columns, not the row, that split the width. Components also have scale and minWidth (default 160), used when several components sit side by side in the same row; you’ll meet those in Chapter 6 on input components.

How do you set these two numbers? Three rules of thumb.

Use integer ratios for scale, not things like 1.37. A ratio is meant to be read by people: in 2:1 the first block takes two shares, so who should be wider needs no figuring out; 1.37:1 only makes the next person to change it guess what you were thinking.

Set minWidth by “how narrow this area can get and still be usable”, not by copying pixels from a design mockup. The input area has to fit an 8-line textbox, so 480 is a reasonable lower bound; the result area only holds short text, so 320 is enough. The problem with copying a mockup is that a mockup has one width, while users’ windows have countless.

A ratio isn’t a “fixed width”. It only decides how surplus space is split, not the minimum usable width. Drag the window from 1280 to 1920 and the two columns are still 2:1, but both get wider; narrow the window from 1280 to 900, the page content width drops to 704, and the two columns have already stacked — because 704 is less than 816. Both behaviors are automatic; you don’t write media queries or prepare a set of sizes for every breakpoint.

One more easily overlooked thing. After stacking, both columns become full-row width. That is, on narrow screens there’s no such thing as a “ratio” — only who comes first matters. So when you write a Row, think about it as you go. If these two blocks stack vertically, is the order still sensible? Put results above inputs and on narrow screens the user sees a bunch of empty boxes first.

4.6 The Effect of visible and interactive on the UI

The last block of the skeleton is the advanced area, visible: false.

using (gr.Row(visible: false))
{
    gr.Markdown("### Advanced options");
    gr.Textbox(label: "Separator", value: ",", info: "What separates multiple values");
    gr.Number(label: "Line limit", value: 200);
}

You can’t see it in Figure 4-3. It isn’t collapsed, and it isn’t hidden. It simply isn’t drawn at all. None of this Row’s three children exist on the page — not even a div is generated — so it takes up no space. Where the advanced area should be, there’s nothing; below the main body is blank space, and below that the footer.

visible has three uses; this chapter uses the first.

  • Hard-coded in the constructor: false means it never appears. Good for “modules not finished yet” — put the code in, keep it off the page for now;
  • Changed at runtime with Update, gr.Update() with { Visible = true }. Good for interactions like “click to expand”; needs events, covered in Chapter 5;
  • Put in an Accordion so users can collapse it themselves. Covered in Chapter 18.

visible: false affects only whether it’s drawn, not the structure. The layout tree in /config still has that row, with the visible attribute set to false, and all three children are still in the tree. So a “hidden block” can still be referenced by events and opened by Update — it just isn’t on the page at this moment. Chapter 5 uses this. To put “Advanced options” under a button’s control, you don’t rebuild the page; you just change visible to true.

interactive governs a different thing: whether it can be changed. “Statistics” and “Notice” in the result area are written with interactive: false — they display results and shouldn’t be editable.

Here’s a counterintuitive detail. A box with interactive: false looks almost exactly like an editable one. White background, dark text, the same border color — the only difference is you can’t click into it, and the cursor is a normal arrow instead of a text cursor. In Figure 4-3, “Body” and “Statistics” both look white for exactly this reason.

“Body” is the opposite: it’s editable, written with interactive: true. That’s not arbitrary. The line-wrapping tool in Chapter 3 lets users hand-edit the wrapped body, then check “Keep my edited body” so the next run won’t overwrite it. The skeleton keeps it editable for now; that switch only makes sense after Chapter 5 wires up events. Click in and change a few characters now and a refresh wipes them, because nothing records the changes yet.

The two parameters together give only three outcomes.

visibleinteractiveWhat’s on the page
truetrueDisplayed normally, editable
truefalseDisplayed normally, can’t click in, looks almost unchanged
falseanyNot drawn at all, takes no space, but still in the structure tree

interactive also has a default behavior, and this chapter’s code happens to trigger it.

On a static page with no events, the framework can’t tell input from output and can only rely on a convention. A component that already has content is treated as an output and rendered read-only; an empty one as an input and editable. “Has content” here is judged by the component’s default value: a textbox that isn’t an empty string, a number that isn’t 0, a checkbox that’s checked — all count as having content.

In the sample, both “Source text” and “Body” are written with a non-empty value; without an explicit interactive: true, they’d be boxes you can’t click into. A reader opens the page wanting to edit the source text, finds they can’t, and starts doubting their own setup.

gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);

In that line, interactive: true isn’t optional decoration; it overrides the convention above.

The checkbox next to it is unaffected. In gr.Checkbox(label: "Keep my edited body", value: false), false happens to be the checkbox’s default, so it doesn’t count as “having content”, and it stays clickable. Change value to true and it becomes non-clickable.

Once Chapter 5 wires up events, this convention gives way to the events. Components used as inputs become automatically editable, those used as outputs automatically read-only, and then you’re fine without writing interactive. But in a static skeleton, write interactive alongside any non-empty value and you save yourself one round of confusion.

One more thing: both visible and interactive can be changed in Update and written on the component. The difference is that in the constructor it’s the initial state, while in Update it’s a change for this one run. The former decides what the page looks like when opened, the latter how it changes during a run. This chapter only has the former.

4.7 Choosing Between Interface and Blocks

Now we can answer a practical question. You have a requirement — Interface or Blocks?

First, one thing: the return type of gr.Interface(...) is itself Blocks. It’s “a fixed layout built with Blocks” — one column of inputs, one column of outputs, one submit button, plus ready-made extras like examples, clear, and flags. So the choice is “use a ready-made layout” versus “place things yourself”.

The criterion is three questions in order; the first “yes” settles it.

  1. Is the UI “a set of inputs → one click → a set of outputs”? Yes, use Interface.
  2. Do you need side-by-side areas, or a containment relationship between areas? Yes, use Blocks.
  3. Do you need to bind events per component, need state, need multiple pages? Yes, use Blocks.

The third follows from the first two. As soon as the UI has two actions, Interface’s single button maps to just one handler function and the second action has no entry point; as soon as data must survive across two operations, you need State (Chapter 14); as soon as there’s too much functionality for one page, you need multiple pages (Chapter 18). All three can only be done in Blocks.

Conversely, when should you not use Blocks? The answer is “when you only need one function”. Interface writes the layout, button, example rows, and clear logic for you — all of which would otherwise be code you’d write. Rewriting a tool with three inputs and one output in Blocks adds a few dozen lines of container code and buys only the possibility that “you might add another area later”. Don’t pay for a requirement that hasn’t appeared yet.

The migration cost between the two is low too. Moving from Interface to Blocks, not a line of business code changes; only three places do.

  • Components change from “stuffed into the inputs / outputs lists” to “placed into containers”;
  • The original submitBtn becomes gr.Button(...), placed in a container;
  • The one run that Interface wired up automatically becomes a Click connecting the button, inputs, and outputs (Chapter 5).

Move the line-wrapping tool from Chapter 3 over and TextLayout.Wrap stays completely untouched; only the Layout handler function changes where its return value goes. What migrates is the UI; the business half moves over as-is.

ScenarioChoiceReason
One function, a few inputs and outputsInterfaceLayout, button, examples all ready-made
Demoing to people, need an examples rowInterfaceExample rows and flags are built in
Two or more side-by-side areasBlocksInterface has only two columns
Grouping needed inside an areaBlocksNeeds containers like Group
Multiple buttons, multiple actionsBlocksInterface has only one submit
Data must survive across operationsBlocksState only exists in Blocks
Too much functionality, needs pagingBlocksMulti-page navigation is on Blocks

This table says one thing: Interface is one fixed arrangement of Blocks. When you can’t decide, write it as Interface first — the part where you get stuck tells you what’s missing.

4.8 Chapter Summary

Blocks writes a page, not a function. A component belongs to the innermost open container. using opens a layer, the closing brace closes it, and later components go back to the previous layer. Omitting using leaves that layer open and everything after gets stuffed into it; writing outside all using blocks throws no error, the component just doesn’t appear on the page. The page is sealed when the first request arrives, and adding components after sealing is rejected, so the UI must be written before Launch.

The four containers have a clear division of labor: Row arranges horizontally and splits width by scale; Column arranges vertically with each child its own block; Group arranges vertically with children joined into one block sharing an outer frame; Form isn’t written — at the end of rendering the framework wraps consecutive form components into a form node, breaking at non-form components like Markdown and Button. Grouping doesn’t distinguish inputs from outputs; even read-only output boxes get wrapped in.

The auto-generated form carries its children’s scale and minWidth, takes no part in width splitting inside a Column, and competes for shares inside a Row. So for oddities like “the heading went beside the fields”, first count who at that level carries a scale. Also, this form is not an HTML <form>. Pressing Enter doesn’t submit; submitting a group of fields together relies on an event listing them in inputs, which is Chapter 5’s business.

scale governs how to split when wide — shares, not pixels; minWidth governs when to stop placing side by side when narrow. The two main columns are 2:1, at a 1280 viewport 800 and 400; narrow the viewport to 700, the available width 576 is less than 480+320, and the two columns stack into one.

A block with visible: false isn’t drawn at all and leaves no empty space on the page, but it’s still in the structure tree and can be reopened by an event. A box with interactive: false can’t be clicked into but looks almost unchanged, so important read-only states should be written into the label or description. In a static skeleton, components that already have content default to read-only (textbox non-empty, number non-zero, checkbox checked); write interactive: true explicitly to make them editable.

Interface is one fixed arrangement of Blocks, and its return type is Blocks. One function with one set of inputs and outputs — use it; side-by-side areas, multiple actions, state, multiple pages — use Blocks.

The next chapter wires events into this skeleton. Clicking a button will actually run a line-wrapping pass, and the outputs will actually change with it. Only then do the positions laid out in this chapter come into play.

Chapter 5. Events and Interaction Bindings

The page in Chapter 4 has a button that does nothing when you click it. This chapter wires it up.

An event is the line between a “component” and a “handler function”. Chapter 3 covered what a handler function should look like, but not how to connect this line; Interface connects it for you, while in Blocks you connect it yourself. This chapter follows the bindings in the sample: trigger conditions, which components to read and write, how repeated clicks are coalesced, and how several steps are chained together.

This chapter’s sample adds two “playgrounds” on top of the skeleton. They exist for this chapter and are separate from the workbench itself. One uses a single input box to show the difference between four events; the other uses three buttons to show coalescing and dropping under repeated clicks. After this chapter you can delete both blocks wholesale without affecting the workbench itself.

Figure 5-1 The UI with events wired up: inputs on the left, results on the right, two playgrounds at the bottom

The page is much longer than in Chapter 4, but the structure is still those three parts: title, main body, footer. The two columns in the main body haven’t changed; what has changed is that they now respond to actions. The two blocks at the bottom are this chapter’s playgrounds; everything from “Event Playground” down can be deleted.

5.1 Trigger Differences Between Click, Change, Input, and Submit

Of the four events, Click is the easiest to understand: a button is clicked once. The other three are all on input boxes, and the difference lies in “what counts as one trigger”.

Start with the conclusion. The figure below shows which events four actions trigger on the same single-line input box.

Figure 5-2 The same input box, and which events each of the four actions triggers

You can read three rules out of the figure.

Input only recognizes user actions. Keystrokes and pressing Enter both fire it; a program writing a value in does not. It answers “did the user touch it?”.

Change only recognizes whether the value changed. Type a key and the value changes, so it fires; a button writes a value in and the value changes too, so it fires just the same. It answers “did the value move?”.

Submit is only on single-line boxes. Press Enter in a single-line input box and it fires; press Enter in a multi-line input box and it’s a newline, so it does not fire. Bind Submit to a multi-line box, put the cursor in it, and press Enter: you only get one more empty line, and the Submit cell doesn’t budge.

The difference between Click and the others is not the trigger condition but the trigger source. The first three come from inside the input box; Click comes from a button. So “the user typed something” and “the user clicked a button” are two kinds of events and shouldn’t be understood together.

The table alone isn’t enough; you have to see it in motion. The sample’s “Event Playground” does exactly that. A single-line box called “Try it”, with four events each writing to its own cell.

Figure 5-3 Type three characters in “Try it”, and both Input and Change move

Type three characters and both the Input and Change cells read “3 characters”. At this point they look identical; the difference comes in the next step.

Figure 5-4 Click “Write example”: Change follows, Input stays at 3 characters

The “Write example” button does one thing: it writes that sample text into “Try it”. That’s a program changing the value, with nobody touching the keyboard. The result is unambiguous. Change becomes 139 characters, Input stays at 3 characters.

Behind these two cells are two bindings; the whole playground has six in total, plus two small functions.

    events.Probe.Input((string s) => Echo("Input", s), [events.Probe], [events.OnInput], triggerMode: TriggerMode.AlwaysLast, apiName: "Try Input");
    events.Probe.Change((string s) => Echo("Change", s), [events.Probe], [events.OnChange], triggerMode: TriggerMode.AlwaysLast, apiName: "Try Change");
    events.Probe.Submit((string s) => Echo("Submit", s), [events.Probe], [events.OnSubmit], apiName: "Try Submit");
    events.Probe.Focus((string s) => Echo("Focus", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Focus");
    events.Probe.Blur((string s) => Echo("Blur", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Blur");
    events.Write.Click(() => SampleText, null, [events.Probe], apiName: "Try Write");
static string Echo(string what, string value)
    => value.Length == 0 ? $"{what} · empty" : $"{what} · {value.Length} characters";

Five of the bindings look much alike: the same input box, the same Echo, each writing to its own cell. The last one is different. It’s the Click of the “Write example” button, writing the sample text into “Try it” to create the “program changes the value” scenario.

That’s the entire disagreement between Input and Change. Which one you pick depends on whether you want to follow “values changed by a program”.

  • Only care about user input? Use Input. For example, feedback that follows your hands like “prompt as you type”.
  • Need to sync whenever the value changes? Use Change. For example, a program backfilling a value, loading a sample, or another component changing the value.

In the sample, the “Source text” box is bound to Change, not Input, and the reason is right here. Next to it is a “Load example” button that replaces the whole source text. If you bound only Input, the character-count label and button state wouldn’t update with it, and the user would see the previous character count.

    input.Text.Change(Count, [input.Text], [input.Text, input.Run], triggerMode: TriggerMode.AlwaysLast, apiName: "Character count");

The triggerMode parameter in this line is covered in 5.4; for now, just remember it has to do with fast typing.

There’s a misconception carried over from web development; let’s dispel it first. Change does not “fire only on blur.” The browser’s native change event does work that way: you edit an input box, click elsewhere, and it fires once. Gradio’s Change doesn’t — it fires on every keystroke. So “bind a Change to query the database” turns into one query per character typed. To prevent that, use the triggerMode covered in 5.4, or simply don’t do heavy work inside Change.

Submit has a narrower place; it only makes sense on single-line boxes. The typical single-line scenario is “enter a name, an address, press Enter to submit”. The user doesn’t have to go looking for a button. Multi-line boxes don’t bind Submit, because Enter there is a necessity (writing the Body needs newlines). If you want “Enter to submit” on a multi-line box, Submit can’t help; you need another approach (more on that in Chapter 6, when we cover Textbox’s button parameters).

Click and Submit often come as a pair: press Enter in a single-line box, or click the button next to it, and the same thing happens. To support both, bind twice — write the same set of inputs and outputs twice, with the same handler function. Whether to give the two bindings different apiName values depends on whether you want to tell them apart in the API; on the UI they do the same thing, so the two bindings can share one name.

One more detail about Click: a button click carries no extra event data. You can’t ask in the handler function “which button was just clicked”. If you want to know “what was in the input box when it was clicked”, list the input box in inputs. Input boxes, on the other hand, can get event data, covered at the end of 5.3.

5.2 Use Cases for Blur and Focus

The two focus events are one in, one out. Focus is the cursor coming in, Blur is the cursor leaving.

In Figure 5-4, the Focus cell reads “Blur · 3 characters”. That’s because clicking “Write example” moves the cursor out of “Try it”, and clicking a button counts as leaving too.

Focus events suit three kinds of things.

Editing-state hints. Show “Editing” when the cursor comes in and “Saved” when it leaves. This kind of hint doesn’t need to know what the value is, only whether the person is there.

Validation on leave. The user fills in one cell and clicks to the next; that’s the most natural moment to validate. It neither interrupts typing nor waits until submit to find a problem.

Drafts. Save the current value on leave, and show “you left off halfway last time” when they come back. For real persistence you have to wait for state in Chapter 14.

It’s not suited to being used as “the value is done changing”. The user may just switch windows or click elsewhere without changing a single character, and Blur still fires. To judge “the value really changed”, use Change.

These two are often used together. Take the “Characters per line” cell: the user enters 5, and you need to tell them “at least 10 characters per line”. The validation itself goes in Change (recompute as soon as the value changes), while the hint’s display timing can go in Blur (only remind them when they leave the cell, without interrupting typing). The benefit of separating them is that the user isn’t chased by red text while still editing, and what needs saying still gets said on leave.

Focus has one other use. It’s the only event that reflects “getting here with the keyboard Tab key”. For keyboard accessibility, Click can’t help; Focus can.

In the sample, both events write to the same cell, so you see the result of the last one. Going in writes “Focus”, coming out writes “Blur”. In real features you’d usually write them into two separate components.

There’s one more side effect of focus to know: clicking a button blurs the input box. In Figure 5-4, clicking “Write example” turns the Focus cell into “Blur” — that’s what this click causes. So a single “click a button” action can send the server two events, first Blur, then Click. If your Blur does heavy work, the user waits extra every time they click a button.

You can also use this the other way around. To keep “save on leave” from blocking a click, put the save in Blur and write the result elsewhere with Update; the click still happens, and neither side waits for the other.

5.3 inputs, outputs, and Handler Function Signatures

One event binding has to state three things: whose event it is, which components to read, and which components to write.

    var arrange = input.Run.Click(Arrange,
        [input.Name, input.Text, input.Width, input.Keep],
        [result.Body, result.Stats],
        apiName: "Clean up");

The first line is “whose event”: the Click of the input.Run button. The second is “which to read”: Result name, Source text, Characters per line, and Keep my edited body. The third is “which to write”: Body and Statistics.

The contract from Chapter 3 still holds here, unchanged down to the letter. However many components are in inputs, the handler function has that many parameters; however many are in outputs, it returns that many values.

What happens when they don’t match is covered in Chapter 3. Too few inputs: the missing parameters get the type’s default value. Too few return values: the missing outputs are cleared. Too many: they’re dropped. None of it raises an error; on the UI it’s just “the result is wrong”. This chapter on events merely moves that into the binding’s two arrays. Get an array wrong and the symptom is exactly the same as a wrong handler function, and harder to spot, because it isn’t in the function signature. After writing a binding, it’s best to check these counts against each other: the number of inputs, the number of parameters, the number of outputs, and the number of return values.

(object, string) Arrange(string name, string text, double? width, bool keep)
{
    if (TextLayout.NameError(name) is { } error)
    {
        throw new ArgumentException(error);
    }

    var result = TextLayout.Wrap(text, width);

    object body = keep ? gr.Skip() : result.Text;

    return (body, Stats(result.Report));
}

Four parameters for four inputs, two return values for two outputs. The reasoning behind the object body line was covered in Chapter 3. That position can be a string or Skip, so it has to fall back to the common parent type.

apiName is new in this chapter. It gives the binding a name that appears in /gradio_api/info and in the public API; if you don’t give one, the framework uses the handler function’s name (the line-wrapping tool in Chapter 2 has endpoints called /lambda or /Split). The sample gives each binding an explicit name such as Clean up. Spaces work in an endpoint name too, so /gradio_api/call/Clean up is valid.

One Kind of Parameter Doesn’t Take an inputs Slot

There is another kind of parameter that isn’t written into inputs: event data. To find out what this trigger brought back, put SelectData in the signature.

    // Illustration: this binding is not in the sample
    text.Change((string s, SelectData d) => $"value={s} Source text={d.Raw}", [text], [outBox], apiName: "with_data");

Two parameters in the signature, only one component in inputs. SelectData doesn’t count as an input slot; the framework fills it in by type. Type abc in the box and the d.Raw the handler function gets is abc.

Different components give different event data. SelectData carries the selected item and index (used most with selection components, met again in Chapter 7), KeyUpData carries the pressed key and current value, LikeData carries the like state. If you don’t need it, don’t write it. Writing it doesn’t take an input slot, but the signature looks more complex than it really is.

The same “what to read, what to write” can hang off multiple events. In the sample, “Clean up” hangs only off Click, but if you want both “click the button” and “press Enter” to clean up, bind once more with Submit and write the same set of inputs and outputs again. From Chapter 6 on you’ll see that one handler function hanging off two or three events is common.

Look at all the bindings in the sample together and you get a fairly useful map.

    // Clean up: the button runs the main step, then records, and finally picks Pass or Fail.
    var arrange = input.Run.Click(Arrange,
        [input.Name, input.Text, input.Width, input.Keep],
        [result.Body, result.Stats],
        apiName: "Clean up");
    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");
    arrange.Success(Pass, [input.Name, result.Stats], [result.Notice], apiName: "Pass");
    arrange.Failure(Fail, [input.Name], [result.Notice], apiName: "Fail");

    // When the source text changes, update the label and button state; both manual typing and "Load example" must keep up.
    input.Text.Change(Count, [input.Text], [input.Text, input.Run], triggerMode: TriggerMode.AlwaysLast, apiName: "Character count");
    input.Load.Click(() => SampleText, null, [input.Text], apiName: "Load example");

Six bindings, all read the same way: whose event, which to read, which to write. The input.Load.Click one has no inputs (null), because “Load example” doesn’t need to read anything. It returns a constant. The handler function is a lambda, one line long; a handler function that short doesn’t need a name of its own.

The null position can also be written as an empty array []; the two forms are equivalent. The sample uses null because it states more clearly that “this event reads no components” rather than “reads zero components”, even though the two are the same thing inside the framework.

A component can be an input and an output at the same time. The sample’s “Run log” does exactly that.

    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");

Record reads three things (result name, statistics, the old run log) and writes back into the run log. Read the old, write the new — this pattern is the only way to make output “accumulate” before there’s state (state isn’t covered until Chapter 14).

string Record(string name, string stats, string log)
    => $"{DateTimeOffset.Now:HH:mm:ss} {name.Trim()} · {stats}\n{log}";

A new line of record is added in front of the old ones, so the newest is on top. This function references no components; it only concatenates strings. The boundary between business logic and UI stays where it was.

The Sample’s Code Structure Changed

The Chapter 4 sample is flat: one using nested inside another, with all the components written inside. That won’t do in this chapter, because a binding uses components from the left and the right at the same time. The “Clean up” button is in the left column, Body and Statistics in the right; when you write the binding, both components have to still be in scope.

So the sample changed to one method per area (BuildInput, BuildResult, BuildEventLab, BuildClickLab), each returning the components it builds.

    InputArea input;
    ResultArea result;
    using (gr.Row())
    {
        input = BuildInput();
        result = BuildResult();
    }

BuildInput still has those using blocks, except that at the end it does return new InputArea(name, text, width, keep, run, load). InputArea is a record; its six fields are those six components. The bindings are written together at the top, accessed as input.Name, result.Body, and so on.

That’s the “write areas as methods” from Section 4.3 of Chapter 4.

InputArea BuildInput()
{
    using (gr.Column(scale: 2, minWidth: 480))
    {
        gr.Markdown("### Text Cleanup");

        var name = gr.Textbox(label: "Result name", value: "Wrapped text", interactive: true);
        var text = gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
        var width = gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
        var keep = gr.Checkbox(label: "Keep my edited body", value: false);

        Button run;
        Button load;
        using (gr.Row())
        {
            run = gr.Button("Clean up", variant: "primary");
            load = gr.Button("Load example");
        }

        return new InputArea(name, text, width, keep, run, load);
    }
}

Compared with the flat code in Chapter 4, there are only two differences: a method wrapped around the outside, and one extra return at the end. The “declare first, assign inside the using” style of Button run; exists because both buttons have to sit in one Row, and variables inside a using block cease to exist once you leave the block.

The record definition is as follows.

sealed record InputArea(Textbox Name, Textbox Text, Number Width, Checkbox Keep, Button Run, Button Load);

It has no methods; it only bundles a few components and carries them out. The field names are exactly the ones used in the bindings, input.Name, input.Run.

5.4 triggerMode and Concurrent Triggers

What about repeated clicks? It’s a question every UI with buttons has to answer.

The sample’s “Repeated Clicks Compared” area has three buttons that do the same thing: wait 600 milliseconds, then report which run this is. Each button has a different triggerMode; click each one four times in a row and the result looks like this.

Figure 5-5 Four repeated clicks each: Default runs once, Last runs twice, All runs four times

Three lines of text, three behaviors.

Default (no triggerMode) runs once. The first click starts the run; the next three arrive before it finishes and are dropped outright.

AlwaysLast runs twice. The first runs immediately, the middle two are dropped, and the last is kept; once the first finishes, that last one is added.

Multiple runs four times. All four run, one after another. The queue lets only one through at a time, so four runs are four 600-millisecond stretches.

Why is the default “drop” rather than “queue”? Because the most common scenario is “the user’s hand slipped and clicked too many times”, not “the user really wants five runs”. A ten-second task clicked five times would queue up fifty seconds of running, and the user would just think the program is broken.

The semantics of AlwaysLast take a little more thought. It guarantees “the last state is always computed”. The user changes parameters a few times, clicks repeatedly, and you want the final result to correspond to the last click, not the first. Use AlwaysLast for that scenario.

Multiple is used less, but it isn’t useless: it’s for occasions where every click should leave a trace. Take a “Record” button — five clicks should produce five records.

What does the user see for the clicks that get dropped? The button is still clickable, and clicking gives no feedback at all. While a 600-millisecond run is in progress, the button is still clickable; clicking it just does nothing. This isn’t a defect. If the button were disabled during the run, the user would think the program froze; keeping it clickable at least avoids the feeling of “I can’t click it”. The cost is that the user may not know their click was ignored. Fixing that takes progress display (Chapter 16) and button state (Interactive in 5.7).

The three modes differ in how they handle repeated clicks. Default holds in exactly one case: repeated clicks should not repeat the run. To guarantee “the final result corresponds to the last click”, use AlwaysLast; to leave a trace every time, use Multiple. When you can’t decide, ask first: the user clicks five times — how many runs do they want?

ScenarioWhich to useReason
Ordinary submit, queryDefaultExtra clicks from a slipping hand shouldn’t cause extra runs
Change a few parameters, then submitAlwaysLastThe final result must correspond to the last click
Every time needs a recordMultipleFive clicks should give five records
Input / Change on an input boxAlwaysLastDon’t let the result stop halfway

One more emphasis on the last row. The first three rows of the table are about “the user clicks a button”; the last row is about “the user types”. The two look like the same thing (both are high-frequency triggers), but typing is denser, so the default “drop” makes the UI visibly lag. In the sample, both high-frequency events Input and Change are written with AlwaysLast; Submit and the focus events are low-frequency to begin with, so they aren’t.

One more thing to make clear: triggerMode is not throttling. Throttling is “run at most once every 200 milliseconds”, and merges the intervening triggers into an average; triggerMode either drops later ones (default), waits for the current run to finish and then adds the last one (AlwaysLast), or runs every time (Multiple). It doesn’t make judgments like “wait until the user stops”. If you want to query after input has stopped for 300 milliseconds, you have to wait in the handler function yourself, or use Textbox’s input throttling parameter (covered in Chapter 6). For this chapter you only need to know that it governs “how repeated triggers are handled”, not “how often to run”.

static class Runs
{
    private static int once;
    private static int last;
    private static int all;

    public static string Once() => Run("Default", ref once);

    public static string Last() => Run("Last", ref last);

    public static string All() => Run("All", ref all);

    private static string Run(string label, ref int counter)
    {
        Thread.Sleep(600);
        return $"{label} · run {Interlocked.Increment(ref counter)}";
    }
}

The three methods differ only in the counter and the wording. Thread.Sleep(600) is deliberate. Real line wrapping takes only tens of milliseconds — so fast that four clicks wouldn’t overlap at all, and you’d never see the coalescing. Slowing it down is what makes the coalescing visible.

The counters sit in static fields only so this chapter can show “how many runs happened”. They belong to the process, not to any one user; real session state is covered in Chapter 14.

The three buttons’ bindings differ by only one parameter.

    clicks.Once.Click(Runs.Once, null, [clicks.OnceLog], apiName: "Repeated Clicks Default");
    clicks.Last.Click(Runs.Last, null, [clicks.LastLog], triggerMode: TriggerMode.AlwaysLast, apiName: "Repeated Clicks Last");
    clicks.All.Click(Runs.All, null, [clicks.AllLog], triggerMode: TriggerMode.Multiple, apiName: "Repeated Clicks All");

triggerMode has one more use, unrelated to repeated clicks: high-frequency events.

Input and Change fire once per keystroke in an input box. A fast typist can hit five or six keys a second, and the default “drop” leaves the UI stuck on the result of the first keystroke. In the sample, both events on “Try it” are written with AlwaysLast, precisely so fast typing doesn’t leave the result halfway. Omit this parameter and a reader typing quickly will see “3 characters” after typing 5, then assume the count is wrong.

5.5 The queue Parameter and Immediate Events

Events go through a queue by default. The queue is a pipe: events come in, line up, and run one at a time (only one runs at a time by default). queue: false turns that pipe off, so the request goes straight to the handler function.

To compare queued and non-queued, use four buttons: two queued, two not, with every handler function waiting 600 milliseconds, then use a tool to click both in the same group at almost the same time.

Queued: A 16352–16964ms, B 16984–17588ms
Not queued: A 18881–19482ms, B 18889–19497ms

The queued group runs one after the other. B starts 20 milliseconds after A ends, so the two stretches barely overlap; the two intervals in the non-queued group almost completely overlap. From the first click to the second result, the queued group takes 1236 milliseconds and the non-queued group 616 milliseconds — exactly double.

When should you turn the queue off?

Turn it off for actions that are quick and must happen immediately. The two focus events in the sample have the queue off. The cursor moving in and out shouldn’t be queued behind typing, or the hint would take ages to appear.

Don’t turn it off for work that writes files, uses CPU, or calls external services. With it off there’s no queue protection, so a few repeated clicks really do run concurrently several times. The whole point of the queue is to line that kind of work up.

Here’s a counterintuitive point to know first. No queue doesn’t mean you can click repeatedly. Click a non-queued button four times and the handler function runs only once. After the click it ignores you for a while, and only recovers when the result comes back. So turning off the queue doesn’t let the same button “run more times”; what it changes is a different thing — whether two different events can run at the same time.

    events.Probe.Focus((string s) => Echo("Focus", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Focus");
    events.Probe.Blur((string s) => Echo("Blur", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Blur");

To see the queue with your own eyes, open the browser’s network panel and click “Clean up”. You’ll first see a POST to queue/join, then a persistent queue/data (an SSE stream), with the result pushed back over that stream. Non-queued requests don’t take this path; they go straight to an immediate endpoint. This difference comes up again in Chapter 16 on streaming output. There, the queue/data stream pushes not just one result but a series of them.

What does the queue mean for the user? It means “after you click, you wait”. When several requests come in, the UI shows a queued or running state (that little spinning icon), and runs the next only after the previous finishes. This is also why the default triggerMode is “drop”. If repeated clicks all queued up, the user would see a long string of waits when they really only wanted one run.

The cost of turning off the queue needs to be clear: there is no queue protection. When two different events trigger the same handler function at once, the two really do run at the same time. If that function writes the same file or changes the same static variable, they’ll collide. In the sample, the only events with the queue off are the two focus ones, and they do only one thing: write a string into a cell, which doesn’t interfere with anything.

If running this action twice would cause trouble, don’t turn off the queue; use triggerMode to block repeats. If running twice does no harm and it must happen immediately, turn it off.

Queue limits, concurrency limits, and per-group throttling belong to Chapter 15. This chapter’s rule is: queue by default, and turn it off only when you’re sure “this action must happen immediately and is quick”.

5.6 Dependency and Chained Steps

One click can set off a chain of things.

Click “Clean up” in the sample and three steps actually run: first wrap the lines and write Body and Statistics, then add a record to the run log, and finally write a notice based on success or failure.

    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");
    arrange.Success(Pass, [input.Name, result.Stats], [result.Notice], apiName: "Pass");
    arrange.Failure(Fail, [input.Name], [result.Notice], apiName: "Fail");

The return value of Click is a Dependency, representing “this one binding”. The chained steps hang off it, with the three methods each handling one segment.

  • Then runs after Click succeeds and before Success;
  • Success runs only when nothing before it went wrong;
  • Failure runs only when an exception was thrown before it.

Each step has its own inputs and outputs, independent of the others. Then reads the result name, statistics, and old log; Success reads the result name and statistics; Failure reads only the result name. They don’t share the main step’s return value. To use the main step’s result, you have to list that component in your own inputs.

On success the UI looks like this.

Figure 5-6 Click “Clean up”: the main step writes Body and Statistics, Then records, Success writes the notice

Failure looks different. Clear the result name, then click Clean up again.

Figure 5-7 Clean up again after clearing the result name: the main step throws, and only the Failure step writes a notice

Read the two figures side by side and you can draw three conclusions.

On success the order is main → Then → Success. In Figure 5-6, the run-log line was written by Then and the notice line by Success; both are there, which means the record was made before the notice was written.

On failure only Failure runs. In Figure 5-7 the run log is empty; Then didn’t run. The Body and Statistics positions are marked “Error” — that’s left by the main step’s exception, not written by Then or Success.

Failure can’t read the main step’s result. It lists only the result name, so what it gets is the empty string left after clearing; if it tried to read Statistics, it would get the value left over from the last success, or empty.

Those two red “Error” marks are added automatically by the framework. When the main step throws, the two positions it would have written are marked as errors, and the message is only two characters long. That feedback is weak: the user can’t tell what went wrong. So the Failure step has to write a sentence in plain language (in the sample it’s “Cleanup failed, the result name can’t be empty”). Turning exceptions into plain language is covered in more detail in Chapter 17. There you get the Error component, runtime prompts like gr.Error, and the ability to tell cancellation, timeout, and real failure apart.

Behind the third conclusion is an easy trap. When the main step throws, its outputs are not cleared. In Figure 5-7, Body and Statistics are marked “Error” because they were empty to begin with; if the previous run succeeded, the values in those two positions are still there, just covered by a red “Error” on the UI so they look gone. Turn that mark off or look from another position and the old values are still there. So in Failure, don’t treat the main step’s outputs as “this run’s result” — they’re always the old ones.

One more thing to add. Success and Failure look only at the main step, not at the steps after it. Make Then throw an exception itself and here’s what happens.

Normal:         Main=main:hi     Then=then:main:hi    Success=success:main:hi   Failure=
Then throws:  Main=main:boom   Then=then:main:hi    Success=success:main:boom  Failure=

In the second line, Then threw an exception (the cell it writes stayed at the previous value then:main:hi), yet Success still ran and Failure didn’t. The reason is that Success / Failure judge the main step’s success or failure, not the whole chain’s. So don’t expect “Then failing will go to Failure”. An error inside Then just means its own cell wasn’t written; everything else goes on as usual.

This rule affects how you split steps. If a later action’s failure must be visible to the user, don’t put it in Then and expect Failure to catch it; either move it back into the main step (make it “part of the main step”) or write the error into one of its own outputs inside that step.

There’s one more thing visible in the browser. One click, and the server receives three jobs. Click “Clean up” and the network panel shows three queue requests. The chain is three jobs queued one after another; the next one’s turn comes only after the previous finishes.

This has two practical effects. One is latency: three steps mean three round trips, a little slower than one run. The other is that each step is an independent event, so each has its own triggerMode, queue, and apiName; the parameter lists of Then and Success are identical to the main step’s, and they aren’t just for show. The sample doesn’t set these parameters and uses the defaults, because none of the three steps is heavy and none needs its own rate limiting; when a step does need separate control over concurrency or the queue, the parameters are given explicitly right here.

So why three steps? Because the three things have different responsibilities.

  • The main step only “computes the result”, with no record-keeping and no notice;
  • Record-keeping is something done “only after success”, so it goes in Then;
  • The notice has two tones, one line for success and one for failure, so it’s split into Success and Failure.

Stuff all three into the main step and the handler function ends up with mixed logic — “first compute, then build the log, then check for an exception and build the notice” — and once an exception is thrown, the code after it is never reached, so the notice can never be written. Chained steps take “the things that still have to happen after an error” out of the main step.

One limitation: a chain hangs only off “that one binding”. If the same handler function is bound to two events (say a button and Enter), the chain has to be hung once on each; it can’t be shared.

5.7 Linking Output Components to Inputs

By now events can fire, read, write, and chain. One common task remains. When an input changes, make other components change with it.

There’s one in the sample. The label above the source-text box shows the current character count; when the source text is cleared, the “Clean up” button turns gray.

Figure 5-8 Clear the source text: the label becomes “Source text (0 characters)”, the Clean up button turns gray, and the results on the right are left as is

Both changes come from the same handler function.

(object, object) Count(string text)
    => (gr.Update() with { Label = $"Source text ({text.Length} characters)" },
        gr.Update() with { Interactive = !string.IsNullOrWhiteSpace(text) });

It returns two Update values: one for the source text (label only), one for the Clean up button (interactivity only).

Why must you use Update here instead of returning a value? Chapter 3 covered it. A return value replaces the component’s displayed content wholesale; Update merges only the properties you name. In this scenario the difference becomes concrete.

  • Return a string to the source-text box and every keystroke replaces the input box’s whole content. What the user is typing gets wiped, and the cursor jumps to the end.
  • Return Update to change only the label, and neither the characters in the input box nor the cursor moves.

Figure 5-8 has one more piece of evidence: none of the four boxes in the result area on the right changed. If this handler function returned “redraw the whole page”, the result area would be cleared or redrawn; it didn’t, because Update touches only the two properties it names. That’s the “no wholesale redraw” from the start of this section. That’s simply Update’s semantics.

Interactive on a button means “can it be clicked”, on an input box “can it be edited”. In Figure 5-8, the orange Clean up button turns pale — that’s the effect of Interactive = false. This isn’t the same thing as the visible from Section 4.6. visible is whether it’s drawn; interactive is whether it can be operated.

There are three common kinds of linking, each with a bigger effect than the last.

Change the label. This is the sample’s kind. Change “Source text” into “Source text (112 characters)”. It moves one property and the rest of the page stays as it is. Good for “letting the user know the current state”.

Toggle a button. Use Interactive. Turn the submit button off when the content is empty and back on when there’s content. That’s friendlier than letting the button throw an error when clicked. The user can see “you can’t click this yet”. You can also use it the other way around: turn it off while a run is in progress and back on when it finishes (used in Chapter 16 on progress).

Hide a block. Use Visible. The advanced area in Chapter 4, hidden by default, is opened from false with Visible. Write gr.Update() with { Visible = true } to make it appear and false to make it disappear. Note the difference from Interactive: Visible = false means it isn’t drawn, Interactive = false means it’s drawn but can’t be operated.

    // Click to expand the advanced area (illustration, this binding is not in the sample)
    return gr.Update() with { Visible = true };

One thing to watch: the fewer properties in Update, the better. Every property you write is another merge on the client; five properties means changing five places at once. The sample writes only two because it really only needs to change two. When you’re tempted to “refresh everything”, ask first: did everything really change? Don’t write the ones that didn’t.

One limitation: Update can change a component’s properties, but not the structure. It can’t conjure up a component out of nothing, and it can’t move a component from one container to another. To change the structure you have to rebuild the page (Chapter 18 on multiple pages has other ways).

Looking back, the choice between Update and “returning a value” was settled in Chapter 3: a value replaces, Update merges. In this chapter on events the difference becomes more practical. A return value is only right for “this component’s content is exactly this run’s result”, like Body and Statistics; as soon as a component carries other state (label, interactivity, visibility), you have to use Update, otherwise you’d have to rewrite all those properties every time, and miss one and you lose one.

5.8 Chapter Summary

Click, Input, Change, and Submit are four different trigger semantics. Input only counts user actions, so programmatic value changes don’t fire it; Change only cares whether the value changed, so anyone changing it fires it; Submit fires only on Enter in a single-line box; Click comes from a button. Focus and Blur handle the cursor moving in and out, good for editing hints and validation on leave, but not for “the value is done changing”.

One binding has to state three things: whose event, which components to read, which components to write. The contract is the same as Chapter 3: number of inputs matches parameters, number of outputs matches return values. A component can be an input and an output at once — that’s how you let output accumulate before there’s state. One handler function can hang off multiple events, and a chain has to be hung once on each.

triggerMode has three settings. Default drops later triggers, AlwaysLast keeps the last one, Multiple runs them all. The default drop is to guard against a slipping hand; AlwaysLast suits “the final state must be right” scenarios, Multiple suits scenarios where every time must leave a trace. High-frequency events should also set AlwaysLast, or fast typing leaves the result halfway.

The queue is on by default, so events run one at a time; queue: false makes it execute directly, and two non-queued events can run at the same time. Turn the queue off only for actions that are “quick and must happen immediately”. No queue doesn’t mean you can click repeatedly: clicking the same button repeatedly still runs only once.

Chained steps. On success it’s main → Then → Success; on failure only Failure runs. Then runs only after the main step succeeds, and Failure can’t read the main step’s result from this run. Splitting “do the work”, “keep the record”, and “report the error” apart is what lets the main step only compute.

Update does linking: it changes only the properties you name and leaves everything else alone. It’s the only way that dares to write back to a component inside an Input event. A return value replaces the whole content; Update doesn’t.

Before writing a binding, ask three questions.

  1. Which event? Only when the user touches it (Input), whenever the value changes (Change), pressing Enter (Submit), clicking a button (Click), or the cursor moving in and out (Focus / Blur).
  2. What to read, what to write? The handler function’s parameters and return values correspond one-to-one with those two arrays.
  3. What about repeated clicks? Default drop, AlwaysLast, Multiple, or turning off the queue.

Answer the three questions and the binding is written. If you can’t, it’s usually the second question you haven’t thought through. Not knowing what to read usually means not knowing at which step to do the work. The three questions work in reverse too: read a binding someone else wrote, break it down along these three lines, and in a few seconds you can see what it does.

This chapter’s sample is much longer than Chapter 4’s, but the structure hasn’t changed: inputs on the left, results on the right, and two playgrounds at the bottom for this chapter. Delete those two playground blocks and what’s left is the workbench itself. It’s already usable. Change the source text, click Clean up, see the result, repeated clicks won’t run five times, and clearing the source text turns the button gray.

The next chapter starts on the components themselves. It begins with text and numeric inputs, filling in the workbench’s input area piece by piece.

Chapter 6. Text and Numeric Inputs

This chapter adds a second module, Snippet. It assembles a title, a body, a short config snippet, plus a mark color, reminder time, summary length, priority, contact email, and share password into one card. Each of the six input components is used once. Figure 6-1 shows the key parameters of each of these six components.

Figure 6-1 The six components, each with only a few key parameters listed

This chapter doesn’t list every parameter one by one. For each component it covers only the ones that make a difference. Change one value and what the UI shows or what gets echoed back changes visibly. You can look up the remaining parameters in the component documentation.

The Snippet module looks like this when it first opens.

Figure 6-2 The Snippet module, six kinds of input, nine cells in total

Fill them in and click “Generate”: a card appears on the right, and the cell below writes the received values out verbatim.

Figure 6-3 After generating, one card, plus eight lines of echoed values

6.1 Textbox: type, Line Count, and Length Limits

Textbox comes in three kinds: plain text, password, and email. The type parameter decides which.

        var mail = gr.Textbox(label: "Recipient email", type: "email", placeholder: "someone@example.com", interactive: true);
        var pass = gr.Textbox(label: "Share password", type: "password", placeholder: "Leave blank for no password", interactive: true);

The one with no type (“Title” in the sample) is the default, text.

type: "text" is the default; it renders as a textarea, even if it is only one line tall. You can see this in the browser. A plain text box and a password box look alike, but the former is a <textarea> and the latter an <input type="password">. So lines only means something for plain text boxes. Password and email boxes are single-line inputs with no height to adjust. All three recognize maxLength. Set maxLength: 5 on a password box, paste 10 characters in, and only 5 remain.

type only changes how the box looks while you type; it doesn’t change the submitted value. All three type values pass a string to the handler function. A password box shows the characters as dots, but submits the plaintext. In Figure 6-3, the “Received values” section reads “Password. hunter2”, which matches the seven dots you see in the input box. A password box is not encryption; it only hides the display. To actually store a password, you have to hash it on the server, and that belongs to Chapter 20.

type: "email" exists for typing convenience. On mobile and desktop browsers the soft keyboard switches to a layout with @ and ., and the input method stops guessing. It does no validation. You can still type abc, and after you click the button it is still submitted exactly as typed. Browsers do check the format of type="email", but only for native form submission, and Gradio’s submission doesn’t go down that path. Treat it as “convenience while typing”, not as “validation”.

Single-Line or Multi-Line

Whether a Textbox is single-line or multi-line is decided by lines, but the behavior is decided by the element the browser gives it. One line tall is <textarea rows="1">, six lines tall is <textarea rows="6">. Both are textareas; the only difference is height. The real dividing line is elsewhere. In a multi-line box, Enter is a newline and does not trigger Submit (Chapter 5). So “should this cell accept multiple lines” decides two things: which height to use, and whether Enter submits.

For one-value-per-cell fields like titles, names, and emails, use the default single line. For things that may have several paragraphs, like body text, descriptions, and logs, give lines a value greater than 1. Don’t set lines: 4 on a single-line box just to “make it look taller”. It becomes a multi-line box, Enter no longer submits, and the user presses Enter thinking nothing happened.

In the sample, all three textboxes are given a value. The title is “Line Wrapping Rules”, the body is two sentences of explanation, and the password and email are left blank. The point of value is “there’s something to click as soon as the page opens”, so the user can try it once without first working out what to fill in. The other two are left blank because there is no sensible default. Giving a password or an email would instead look as though they had already been filled in.

value is used only once, when the page opens. After the user edits the box, it follows the user’s input, and only returns to value when you refresh the page. To “restore the box to its default when a button is clicked”, you have to return that default value from the handler function (the three ways to return, in Chapter 3).

lines and maxLines are a pair. lines is the initial height; maxLines is the upper bound for automatic growth.

        var body = gr.Textbox(label: "Body", lines: 4, maxLines: 8, value: SampleNote, interactive: true);

This box opens 4 lines tall. Paste 12 lines in and it grows on its own, stops at 8 lines, and the rest becomes scrolling. In the developer tools you can read two heights: 98 pixels before filling, 177 pixels after pasting 12 lines. That’s about 8 lines. Give lines without maxLines and it keeps growing until it pushes the content below off the screen. Give it an upper bound and it stops there.

maxLength is a hard truncation, and it happens in the browser.

        var title = gr.Textbox(label: "Title", value: "Line Wrapping Rules", maxLength: 20, placeholder: "Up to 20 characters", interactive: true);

Paste 30 characters into this box and only the first 20 remain; the extra characters never get in at all. The handler function receives the truncated 20 characters and doesn’t need to cut them again. This is not the same as “the type can’t hold it” from Chapter 3. That one is a runtime error; this one stops the overflow at the input stage.

placeholder is the gray text in an empty box, not a value. When the box has no content it shows “Up to 20 characters”, and it disappears as soon as you start typing; it comes back after you clear the box, but clearing submits an empty string, not that hint. Using value as a hint is a common mistake. The hint then gets submitted as real content.

placeholder and label do different jobs, and you should write both. label says “what this cell is” and stays above the box the whole time; placeholder says “what to fill in” and is gone the moment typing starts. Write placeholder without label and, once the user has typed something, they can no longer tell what the cell is for. This is worst on a long form, when they look back over it.

How the Password Box Actually Behaves

type: "password" is a real password input in the browser, which brings two side effects. First, the browser’s password manager recognizes it. As soon as the page opens it may pop up a “save password” prompt, or autofill the password saved last time. Second, its value doesn’t take part in spell checking and doesn’t support auto-capitalization, so a typo gets no wavy underline.

What gets submitted is plaintext. The “Received values” section in Figure 6-3 is the evidence. The input box shows seven dots, and the handler function gets hunter2. So a password box can stop the person next to you from seeing it, but not the program. This value should never appear in logs, run logs, or exported files. The “Received values” section in the sample is only there so you can see it really is plaintext; in a real application you’d remove that line.

There is one more parameter to cover, submitBtn.

            // Illustration: this field is not in the sample
            sub = gr.Textbox(label: "Box with a button", placeholder: "Press Enter or click the button on the right", submitBtn: true, interactive: true);

Give it true and a small button appears on the right inside the box; clicking it is the same as pressing Enter in that box. It fires the Submit event (Chapter 5). It suits single-line boxes. The user fills in one line and doesn’t have to move their hand down to a button below.

6.2 Number: Precision and Value Range

Number passes a double to the handler function, but three parameters change that value: precision, minimum, and maximum.

        var priority = gr.Number(label: "Priority", value: 2, minimum: 1, maximum: 5, step: 1, precision: 0, interactive: true);

precision: 0 means no decimals. Change precision to 2, type 2.567, and the handler function gets 2.57. It’s rounded to two places before submission. The value itself is changed, not just its display format.

Watch the type too: Number always passes a double, even if you only want integers. precision: 0 merely erases the decimal places; the value is still the double 2.0, not an int. To use an int in the handler function, declare the parameter as int and the framework converts it once according to the declaration (Chapter 3); if you don’t want the conversion, round it yourself inside the function.

minimum and maximum mark out the acceptable range. A value outside the range isn’t clamped to the boundary; instead the whole event fails. Figure 6-4 is the result of entering 9 for Priority (upper bound 5) and clicking Generate.

Figure 6-4 An out-of-range number, the input box turns red, the event fails

The input box turns red first. That’s the browser’s built-in validation; <input type="number" min="1" max="5"> does this by nature. After you click Generate, a red “Error” appears above each of the two output positions. The value failed validation, so the handler function didn’t run to completion.

Notice that the content in those two positions hasn’t changed. The card still reads “Not generated yet.”, and the echo box is still empty. The error is a mark added on top of the existing content, not a replacement. So when you see “Error”, don’t assume the line below was computed this time; it may be left over from the previous run.

This rule runs against many people’s intuition. Most UIs clamp an out-of-range value to the boundary or pop up a hint; here nothing is clamped and it just fails. So when you use Number, set minimum and maximum for values that “really must not be exceeded”, not for values that are “roughly in this range”. If you want a loose range, don’t set them at all and judge in your business logic.

step doesn’t take part in validation. It only affects the increment of the input box’s up/down arrows and where the slider track can stop. Set step to 0.5 and type 7.3: the browser considers the value invalid (stepMismatch), but the value is still submitted and the handler function gets 7.3. To block values like this, you have to check them yourself in the handler function.

What the Number Box Looks Like in the Browser

Number renders as <input type="number">, and the browser gives it a set of built-in behaviors. On the right are two small up/down arrows; one click adds one step. After focusing, the arrow keys also add and subtract. Some browsers even let the scroll wheel change the value. These behaviors are tied to step, so if step is wrong, the user presses an arrow and thinks “why did it jump so far in one go”.

Scroll-wheel changes are an easy place for trouble. Rest the mouse over a number box and scroll the page, and the value changes even though the user never meant to. With many number boxes in a form this drives people mad. The only ways to avoid it are to put the number box farther from the scrolling area, or just use Slider instead — a slider doesn’t respond to the wheel.

precision affects the value itself, not the display. Type 2.567 with precision: 2 and the handler function gets 2.57. Changing only the display without changing the value would be a different matter, and there’s no switch for that here. For “keep full precision in the value, truncate only for display”, you have to format it yourself.

minimum, maximum, and step together decide “which values are legal”. For example, with minimum: 1 and step: 0.5, the legal values are 1, 1.5, 2, 2.5…; with minimum: 1 and step: 0.3, they are 1, 1.3, 1.6…. When you set these parameters, take a moment to ask whether that string of numbers is what you want, especially when you give all three at once. A combination that doesn’t line up leaves the browser permanently red, and the user can’t see what’s wrong.

Values like amounts of money, which can’t have binary rounding error, can be entered with Number, but don’t do the arithmetic with double. It passes a double to the handler function, so the whole 0.1 + 0.2 problem is still there. The approach is the same as in Chapter 3. The UI gives you a double; convert it to decimal the moment it reaches the business layer.

What the User Sees When an Out-of-Range Value Fails

Going out of minimum / maximum bounds is a poor experience. In Figure 6-4 the user types 9 and the input box only gets a red border. No text explains why it’s red. After clicking “Generate”, the two output positions on the right turn into “Error”, again with no explanation.

The only clue the user gets is that red border, and it appears “as soon as they finish typing”, not “only after clicking”. That’s actually an advantage — at least they don’t have to wait for submission. But it also means the range should be set a little wider: don’t write values that “shouldn’t occur in business terms” into maximum. A user who types 9 once in a while is just probing the boundary, and failing the whole event for that is too heavy. Leave the range for values that are “physically impossible” (a negative weight, a percentage over 100%), and put business rules in the handler function, where you can give a sentence in plain language.

The number box also has placeholder; after you clear it, a line of gray text appears in the box. Priority in the sample doesn’t have one, because the 1-to-5 range is obvious at a glance. If the range is hard to guess (say 0.5 to 3.5), writing placeholder: "0.5 – 3.5" is much friendlier than letting the user see a red border first.

There are a few easy traps on the empty-value side. Clear a number box and a non-nullable double parameter gets 0, with no error.

Cleared → Priority: 0

In the sample, “Priority” is a double, so after clearing, the card reads “Priority 0”. That 0 was converted from null; the user filled in nothing. To tell the two cases apart, declare the parameter as double?. Clearing then gives null, and typing 0 gives 0. Chapter 3 covered this rule; here you can see what it looks like on a real UI.

It’s even more obvious when the time box is left empty. A non-nullable System.DateTime parameter gets 0001-01-01 00:00, that is, default(DateTime). In the “Received values” section of Figure 6-3 the time line is filled in; clear the reminder time and click Generate again, and that line becomes 0001-01-01 00:00. This value raises no error and doesn’t warn you that “nothing was entered”; it just quietly appears on the card.

6.3 Slider: Values and Step Size

Slider and Number both pass a double to the handler function; the difference is how the value is obtained. Slider can only take values by step within a range, while Number accepts any number that passes validation.

        var summary = gr.Slider(label: "Summary length", minimum: 10, maximum: 120, step: 10, value: 40, interactive: true);

This slider runs from 10 to 120 in steps of 10. It looks like a track, but there is actually a number box beside it. That box and the track are two ways of entering a value into the same component: drag the track to change the number, type a number to change the track.

The track snaps to the step. With a step of 10, the track has only the positions 10, 20, 30, 40…; force the track’s value to 33 and it lands on 30. The two positions nearest 33 are 30 and 40, and it takes the closer one. So you can’t drag a “33” out of the track.

The number box beside it doesn’t care. Type 33 straight into the number box and press Enter, and 33 is what gets submitted. The track jumps back to 30, the number box keeps 33, and the handler function gets 33. Like Number’s step, the number box only affects the increment and does no validation.

This property decides what Slider is good for: a fixed range and coarse adjustment. For quantities where “being a little off doesn’t matter”, like font size, opacity, and summary length, a slider beats a number box, because the user doesn’t have to think of a specific value — they drag until the number shown beside it looks right. The other way around, for a quantity like Priority that “must be an integer from 1 to 5”, Number fits better. A slider can do it too, but the user has to keep an eye on the number beside it.

value is the starting position. Without value, the slider stops at the lower bound. For a 10-to-120 slider, the initial value is 10. That’s usually not what you want (“Summary length 10” is too short), so always write value for a Slider.

You should use the slider’s info parameter; it adds a line of small text below the track. The track itself can only express “larger and smaller”; it can’t express “what this value means”. A line like “about how many characters per line” or “10 to 120, affects summary length” is more useful than making the user guess.

Dragging the track suits “getting a feel”, and typing a number suits “knowing you want 80”. Both ways change the same value, so you can treat the track as coarse adjustment and the number box as fine adjustment.

You can also operate a slider from the keyboard. After focusing it, the left and right arrow keys move one step per press; hold Shift and some browsers move ten steps. This matters for keyboard users, who can’t use a mouse-only UI.

Slider or Number

Both components pass a double to the handler function; which one you pick depends on “whether the user has a specific number in mind”.

ScenarioWhich to useReason
Font size, opacity, summary lengthSliderBeing a little off doesn’t matter; dragging to find the feel is fastest
Priority, quantity, page numberNumberMust be a specific integer
A percentage with clear upper and lower boundsSliderThe track itself is the “can’t go beyond” hint
Amounts, measurementsNumberNeeds precise input a slider can’t give; convert to decimal in the business layer

There’s one more practical difference: Slider has no “empty” state. It always has a value; if the user doesn’t drag it, the value is the one value gave. So you can’t use Slider where “this field may be left blank” — there’s no way to express “blank”. A cleared Number can express it (with double? you get null).

6.4 Code: Language, Line Wrapping, and Line Numbers

Code is a text box with highlighting; the value is still a string. What it adds is “how this text is displayed”: which language to highlight as, whether long lines wrap, and whether to draw line numbers.

        var snippet = gr.Code(label: "Config snippet", language: "json", lines: 3, maxLines: 6, wrapLines: true, showLineNumbers: true, value: SampleCode, interactive: true);

lines and maxLines follow the same rules as Textbox: initial height and the upper bound for automatic growth. Paste in code longer than maxLines and the editor grows to the limit and stops; the rest takes scrolling to see. So how much you give maxLines depends on “how many lines you want visible at a glance”. Give it 6 lines and the user can probably see a whole function at once; give it 20 and the whole form gets stretched very tall.

wrapLines decides what happens to long lines. With it on, a long line folds onto the next line and the editor gets taller; with it off, long lines don’t fold and a horizontal scrollbar appears. It’s on in the sample. The config in Figure 6-2 doesn’t fit on one line and wraps into two; with it off, you’d have to drag horizontally to see the right half. A config snippet is meant to be read by people, and horizontal scrolling makes them miss the end.

showLineNumbers decides whether that column of line numbers on the left is drawn. Line numbers help when reading code (“the field on line 12”), but aren’t much use when reading config.

Dividing the Work Between Code and Textbox

Both components accept text and both pass a string; choosing between them comes down to one thing. Should this text be read as code?

Use Code for text that’s read as code (JSON, SQL, scripts, config files). It gives you a monospace font, syntax highlighting, line numbers, bracket matching, and a set of code-editor shortcuts (indent, comment, find). Together these make reading far easier than in a plain text box.

Use Textbox for text that isn’t read as code (body text, descriptions, logs). Turning on syntax highlighting for a passage of prose only makes it busier, and line numbers mean nothing there.

There’s one more use. Code with interactive: false works as read-only code display. It’s better than Textbox’s read-only mode because of the highlighting and line numbers, and less work than hand-assembling a piece of Markdown, since you don’t have to worry about backticks and escaping. Chapter 8 compares this again when it covers display components.

The Wrap-Lines Trade-off

Whether wrapLines is on or off depends on “how long a line of this code is”.

For things with a few dozen characters per line, like config files and SQL queries, wrapping on is more comfortable. Turn it off and long lines have to be dragged horizontally, so readers easily miss the right side. But for code where “one line is one complete expression”, wrapping off reads better, because folding cuts a statement up until you can’t see its structure.

The sample chooses on. That card is meant to be looked at, not copied and run; reading smoothly matters more than preserving the exact formatting.

A word on where language’s list comes from. Highlighting is done by the front end, and the front end only knows so many languages. You can still write a language that isn’t on the list; it just won’t be highlighted. But Code’s choice is to throw an exception, not fall back to plain text. So when you hit a language outside the list (C#, for example), either pick a close one (c) or don’t give language at all.

One more thing connects to Chapter 4: Code is not a form component. Chapter 4, on automatic form grouping, said that consecutive form components get wrapped into a form; Code isn’t among them and breaks the grouping up. In the sample, “Config snippet” sits between the Body and the Mark color, so the grouping there is cut in two by it. This has no effect on layout; it just adds one more break in the structure tree.

6.5 ColorPicker and DateTime

Both components have only one value, but the shapes of those values differ a lot.

ColorPicker passes a string to the handler function, of the form #3366cc.

        var color = gr.ColorPicker(label: "Mark color", value: "#3366cc", interactive: true);

Click it open and you get a color palette; after choosing, the input box holds those seven characters. It makes no judgment about “whether the color looks good”, and it doesn’t accept color names like red. Once you’ve chosen, what you get is #rrggbb; if you never chose, it’s null. To use it, parse those seven characters in your own code.

In the sample this color is only written into the card’s footer (“Mark color #3366cc”); it doesn’t actually color anything. That’s deliberate. The Markdown component sanitizes HTML by default (Chapter 8), so stuffing <span style="color:..."> into it gets cleaned out. To really make the color take effect you have to go through CSS (Chapter 19), or use a component that supports styling. In this chapter, ColorPicker passes the handler function a seven-character string — not a color object and not a Color struct.

DateTime is a bit more complex; three parameters decide what it passes to the handler function.

        var when = gr.DateTime(label: "Reminder time", type: "datetime", includeTime: true, timezone: "Asia/Shanghai", interactive: true);

type decides the type, and has only three legal values.

typeThe handler function getsThe same moment (2026-11-20 09:30, Shanghai)
timestamp (default)long, Unix seconds1795138200
datetimeSystem.DateTime2026/11/20 09:30:00
stringstring"2026-11-20 09:30:00"

The sample uses datetime, so the handler function signature writes System.DateTime when. Note that you have to write the full name: after using Gradio.Net;, DateTime refers to the component type, not System.DateTime. Writing DateTime when won’t compile, because that’s the component’s type.

includeTime decides whether the input box asks for hours, minutes, and seconds. Give it false and the hint in the box becomes YYYY-MM-DD, and only the date part is submitted.

Date only (type: string, includeTime: false) → "2026-11-20"

timezone decides how “the local time in the input box” is converted into a timestamp. Leave it out and the machine’s time zone is used. Fill in Asia/Shanghai and the 09:30 the user sees is understood as Shanghai time; open it on a machine in London and the same 09:30 is still treated as Shanghai time, so the timestamp doesn’t change. This parameter really takes effect only with type: "timestamp". datetime and string submit “that time literally”, with no time zone attached.

There’s one detail about the DateTime that datetime passes to the handler function: its Kind is Unspecified. The “Received values” section in Figure 6-3 reads “Time. 2026-11-20 09:30 (Unspecified)”. In other words, this object doesn’t know which time zone it belongs to. Using it as local time is fine, but before you use it for cross-time-zone conversion you have to add the time zone information first.

Choosing Among the Three Types

timestamp, datetime, and string correspond to three uses.

To store, compare, or sort, use timestamp. A long has no ambiguity: in a database it’s one integer column, adding and subtracting are seconds, and sorting is comparing magnitudes. The trouble is display; you have to convert it back to local time before showing it to the user.

To do date arithmetic in C# (add three days, get the first of the month), use datetime. What you get is a System.DateTime, so AddDays and ToString("yyyy-MM") work directly. The cost is that it carries the Unspecified time-zone marker, which you have to fill in before passing it across time zones.

To display and pass through exactly as entered, use string. If the user types 2026-11-20 09:30:00, the handler function gets exactly that string, down to the last character. It suits cases where “this time is only a label and needs no calculation” — like the “Reminder time” on the card, which is only written for people to read.

The sample uses datetime, because the card has to format it as yyyy-MM-dd HH:mm, and that’s the most direct way.

Time Zones

The timezone parameter is easy to overthink. It does exactly one thing: converts that string of local time in the input box into a timestamp using the specified time zone.

Fill in Asia/Shanghai, the user writes 09:30 in the box, and the framework treats it as Shanghai time and computes the matching timestamp. Leave it out and it uses this machine’s time zone.

Where it’s genuinely useful is “the machine’s time zone can change”. Use the program abroad and the system time zone changes with it, so the timestamp computed from the same 09:30 changes too. Hard-code Asia/Shanghai and the value stays stable.

includeTime: false is a separate matter. It narrows the input box to a date only, the placeholder changes from YYYY-MM-DD HH:MM:SS to YYYY-MM-DD, and the submitted value has no hours, minutes, or seconds either. Use it for fields that “only care which day”, like birthdays and deadlines; it saves the user the trouble of filling in 00:00:00.

The input format is fixed: YYYY-MM-DD, or YYYY-MM-DD HH:MM:SS with time. It doesn’t accept 2026/11/20 or “November 20” the way some people expect. Get the format wrong and the value isn’t accepted. This format takes some getting used to, but it’s unambiguous: month and day don’t swap places because of regional habits.

6.6 Input Component Values and Out-of-Range Behavior

The six components pass values of only three types to the handler function.

ComponentType passed to the handler functionWhen empty
Textbox (all three type values)string""
Numberdouble0, or null with double?
SliderdoubleNever empty, always has a value
Codestring""
ColorPickerstringnull
DateTimelong / DateTime / stringnull

With this table you can write a handler function signature straight from it, without trial and error. The table in Chapter 3 was the “component → type” contract; this one extends it. The five extra components all have types that fall within these three.

Three Questions to Ask About Any Field

Choosing a component isn’t a matter of memorizing parameters; it’s a matter of asking three questions.

Question one. Is what the user fills in “free text” or “picked from a range”? Free text is Textbox; for picking from a range, look at how big the range is. Numbers use Number or Slider, colors use ColorPicker, times use DateTime. The next chapter adds the “picked from a set of options” kind too.

Question two. Does this value have a hard boundary it “must not exceed”? If it does, write it into the parameters (maxLength, minimum / maximum, step). If it doesn’t, don’t. Writing it anyway just gives the user a red box they can’t explain.

Question three, what does empty mean? Three answers: empty means “not filled in” (use a nullable type), empty means a default value (use a non-nullable type plus a default in code), or empty is treated as invalid (blocked in the parameters or in the business logic). Answer this clearly and the handler function’s signature is settled.

In the sample, the answers for the six fields are: the title and body are free text, and empty is invalid (an empty title leaves the card with no name); the config snippet is free text but read as code, and empty is allowed; the color and time are “picked from a range”, and empty means not filled in; summary length is a slider and has no empty state; priority empty means not set, represented by 0.

Handle Empty Values Uniformly

The six components behave differently when empty. Textbox and Code give an empty string, Number gives 0 or null, and ColorPicker and DateTime give null. If every handler function writes its own check, the same “not filled in” ends up with six different spellings.

The way to handle it is, unify them into one representation on the very first line of the handler function. For example, convert them all to string?, or check them all once before moving on to the business logic. The sample’s Compose doesn’t do this (it splices the received values straight into the card and shows blanks as blanks) because this module’s output is only a card, and an empty field doesn’t affect correctness. A module that really does validation (like the text cleanup in Chapter 5) should judge them all uniformly at the entry point and only then move on.

The empty-value shapes the components give aren’t uniform; your handler function should make them uniform.

Put this chapter’s six components into one signature and it looks like this.

(object, string) Compose(
    string title,
    string body,
    string snippet,
    string color,
    System.DateTime when,
    double summaryLength,
    double priority,
    string mail,
    string pass)

Nine parameters for nine inputs. Three strings come from the three textboxes, snippet from Code, color from ColorPicker, when is a System.DateTime (type: "datetime"), summaryLength from Slider, priority from Number, and mail and pass are two more textboxes. If all the types line up, the function runs; if even one doesn’t, the UI just shows “Error”.

To know what type a component passes, look at its position in the signature.

Going out of range has four behaviors, all different.

Truncation. The part beyond maxLength never gets in at all, and the handler function receives the truncated value. This is the only out-of-range case that’s “handled automatically”.

Snapping. When you drag a Slider track, the value is pulled to the nearest step position (with a step of 10, 33 lands on 30). The number box isn’t subject to this.

Failure. A Number value beyond minimum / maximum turns the input box red, the event fails after the button is clicked, and the output positions are left with only “Error”. The handler function gets neither this value nor any other.

Let through. A Number’s step doesn’t line up (7.3 against a step of 0.5); the browser marks it invalid, but the value is submitted anyway. You have to check this kind yourself.

Put the four into a table, and when you hit an out-of-range value, check which kind it is first.

BehaviorWho does itExampleWhat the user sees
TruncationThe browsermaxLength exceededThe extra characters can’t be typed in
SnappingThe browserDrag a Slider track to 33 (step 10)Lands on 30
FailureThe browser + the frameworkNumber beyond maximumRed border, only “Error” left after clicking the button
Let through—Number’s step doesn’t line upNothing happens, the value is submitted anyway

Of these four, only “Failure” is a hard block. So when you use input components, think of boundaries in two places: what parameters can block (length, range) goes into the parameters; what parameters can’t block, or block too harshly (step, business rules), goes into the handler function.

One more rule of thumb. Wherever “not filled in” and “typed 0” have to be told apart, declare the parameter as double?. In the sample, Priority is written as double, so after clearing, the card shows 0. In a “1 to 5” priority that doesn’t matter, because 0 already means not set; but if the number were a “discount rate” or a “weight”, 0 and “not filled in” would be very far apart.

6.7 Chapter Summary

Textbox has three type values, and all submit a string. A password box only hides the display; the value is plaintext. lines is the initial height, maxLines is the upper bound for automatic growth, maxLength truncates hard in the browser, placeholder isn’t a value, and submitBtn adds a button inside the box that’s equivalent to Enter.

Number’s precision rounds before submission; going beyond minimum / maximum makes the whole event fail instead of clamping; step only affects the increment and takes no part in validation. When cleared, a non-nullable double gets 0; only double? gets null.

Slider can only take values by step, and a value off the step is snapped to the nearest legal one. It suits quantities with a fixed range and coarse adjustment; for precise input use Number.

Code’s language only recognizes a fixed list, which doesn’t include C#; a wrong value throws an exception at construction. wrapLines decides whether long lines fold or scroll horizontally, and showLineNumbers decides whether line numbers are drawn. Code isn’t a form component and breaks up form grouping.

ColorPicker passes the handler function a #rrggbb string. DateTime’s type decides whether the handler function gets a long timestamp, a System.DateTime, or a string; includeTime decides whether hours, minutes, and seconds are included; timezone only joins the conversion in timestamp mode. The object that datetime passes to the handler function has Kind Unspecified.

The six components’ values fall into three types: string, number, and time. Going out of range has four behaviors — truncation, snapping, failure, and letting through — and only “Failure” is a hard block. What parameters can block goes into the parameters; what they can’t goes into the handler function.

This chapter’s content, gathered into one note.

  • For a text box, first decide single-line or multi-line, then whether you want maxLength; a password box only hides the display, the value is plaintext.
  • minimum / maximum on a number box are hard boundaries; going beyond fails the whole event. step isn’t a boundary, just an increment.
  • A slider only takes values by step and suits coarse adjustment; for precision and for allowing empty, use a number box.
  • A code box’s language only recognizes that list, which has no C#; set wrapLines and showLineNumbers according to “who it’s for”.
  • A color gives a #rrggbb string; a time gives one of long / DateTime / string.
  • Empty-value shapes aren’t uniform; make them uniform in the handler function.

The next chapter switches to a different batch of components. It lets the user pick from given options instead of typing freely. What’s hard about that batch isn’t the parameters; it’s “where the options come from, and what gets submitted after picking”.

Chapter 7. Selection Components

The six components in Chapter 6 are all “fill in freely”: you type whatever text you like, enter whatever number you like. This chapter switches to a different kind, picking from a given set of options. The user doesn’t have to think about the format and can’t enter an unexpected value.

The workbench adds a third module, Filter. It takes a list of “Tag Content” entries, filters them by tag, then sorts them in some order, keeps only the first few, shows only a few columns, and deduplicates by content. Each of the four selection components is used once, which ties together everything this chapter covers.

The four components pass different parameter types to the handler function. For the same “one item selected”, single-select gives a string, the toggle gives a bool, and the two multi-selects give a group of object; for the same “nothing selected”, the four components also behave differently. Figure 7-1 is the comparison table.

Figure 7-1 The parameter types the four components pass back to the handler function

The following sections take them one by one. Here is what the module looks like when it first opens.

Figure 7-2 The Filter module, tags empty, sort and count already have default values

The “Tag” cell is empty, “Sort” already reads “Source text”, and “Count” already has “All” selected. The first is the automatically selected first item; the second is a value the sample gives explicitly. The two defaults come from different places, and 7.7 explains the difference.

7.1 Dropdown: Single-Select and Multi-Select

Dropdown has one switch, multiselect. Leave it out and it is single-select; write true and it is multi-select.

        var tags = gr.Dropdown(label: "Tag", choices: TaskFilter.AllTags.Select(tag => new Choice(tag)).ToArray(),
            multiselect: true, allowCustomValue: true, maxChoices: 3, numChoicesShown: 6, interactive: true);
        var sort = gr.Dropdown(label: "Sort", choices: new[] { new Choice("Source text"), new Choice("By tag"), new Choice("By length") }, interactive: true);

These two lines are two uses of the same component. tags is multi-select and can pick several tags at once; sort is single-select and can have only one sort order.

What is selected also looks different in the UI. A single-select dropdown shows the selected item right in the box, and the box stays one line; a multi-select dropdown turns each item into a small chip (the “To-do ×” in Figure 7-3), and the box grows taller as you add options. This is the same component looking different in its two modes, not two components.

The small-chip design has a side effect. Select a lot and the box keeps growing, pushing the content below down. So a multi-select dropdown is a poor fit for cases where “someone might pick dozens”. For that you want a CheckboxGroup with scrolling, or you simply shouldn’t make people pick one by one. That is half the reason the sample sets the limit to three.

Figure 7-3 Two tags selected, sorted by length, first three kept

In Figure 7-3 you can see the division of labor among this chapter’s four components: tags are two small chips (multi-select dropdown), sort is one line of text (single-select dropdown), count is three dots (radio buttons), and “Which columns to show” is three boxes plus a half-selected select-all box (checkbox group). The two cells on the right are the result and the summary.

The multi-select list doesn’t collapse after you pick one item. You can click several in a row; it closes only when you click outside the box. Each selected item shows as a small chip with a × on its right; click that to remove the item.

When to Use Multi-Select

Single-select and multi-select decide semantics, not just “can you pick more than one”.

Single-select suits “you must pick one of these, and only one”: sort order, unit, status. The user has only one answer in mind; multi-select would just make them hesitate.

Multi-select suits “you can pick zero, one, or several”: tags, columns to show, steps to run. Its empty state is meaningful. “Pick none” often means “no restriction” or “do nothing at all”, and neither of those meanings has a place in single-select.

That is why “Sort” is single-select and “Tag” is multi-select in the sample. There can be only one sort order, while several tags can apply at once.

Where the Options Come From

choices is a Choice list, so it can be built from anything: literals written in code, a static array in the business library, records read from a file or database. The sample uses both. Tags come from TaskFilter.AllTags in the business library; sort is hard-coded in the UI.

The order of the options is the order they are shown, and also the order of the indices in type: "index". To sort alphabetically, sort them before passing them in; to put “the common ones first”, do the same. The component doesn’t sort for you; it draws them in the order you give.

What happens if options repeat? Two Choices with the same value but different labels produce two rows in the dropdown that look different but return the same value when selected. Whichever the user picks, the result is the same, which looks like a bug. Deduplicate before passing them in, or make sure the values are unique.

(string, string) Filter(
    string items,
    object[] tags,
    string sort,
    string count,
    object[] columns,
    bool dedupe)

This is the signature of the filter step in the sample. Six parameters for six inputs; the second and the fifth are both object[]. Tags are a multi-select dropdown, “Which columns to show” is a checkbox group, and the two multi-selects give the same kind of container. 7.5 expands on the other ways this container can be declared.

The tags and columns parameters can’t be passed straight into the business layer. They are containers of object, and the business layer wants strings, so the handler function converts them first.

    var options = new FilterOptions(
        tags.Select(tag => tag?.ToString() ?? "").Where(tag => tag.Length > 0).ToArray(),
        sort,
        count,
        columns.Select(column => column?.ToString() ?? "").ToArray(),
        dedupe);

The question mark in tag?.ToString() ?? "" is necessary. The container’s element type is object, so in theory it could be null. Where(tag => tag.Length > 0) also drops empty strings along the way. If a user defines an empty value, it shouldn’t be treated as a tag.

The Whole Path from Control to Business Logic

Walk through these six parameters and you can see the boundary between the UI and the business logic.

  1. In the UI the user picks tags, chooses a sort order, sets the count, checks columns, and toggles dedupe;
  2. They click “Filter”, and the framework stuffs the six components’ values into Filter’s six parameters in order;
  3. Filter converts the six values to strings (object → string) and packs them into a FilterOptions;
  4. TaskFilter.Run in the business library takes those options and the list of entries and computes the result;
  5. Filter joins the result into two pieces of text and returns them to the two output components.

Step 3 is new in this chapter. In earlier chapters, components passed the handler function exactly the types the business layer wanted (string, double, bool); this chapter adds an intermediate state of “a container holding object” that has to be converted at the UI layer. Once it is in FilterOptions, the business side sees a clean array of strings and has no idea whether the UI used a dropdown or a checkbox group. This boundary is the one from Chapter 3, just with one more conversion.

Step 4 lives in core and is all the business rules of this module.

    public static FilterResult Run(IEnumerable<string> source, FilterOptions options)
    {
        var rows = source
            .Select(line => line.Trim())
            .Where(line => line.Length > 0)
            .Select(Parse)
            .ToList();

        var total = rows.Count;

        if (options.Tags.Count > 0)
        {
            rows = rows.Where(row => options.Tags.Contains(row.Tag)).ToList();
        }

        if (options.Dedupe)
        {
            rows = rows.DistinctBy(row => row.Text).ToList();
        }

        rows = options.Sort switch
        {
            "By tag" => rows.OrderBy(row => row.Tag, StringComparer.Ordinal).ToList(),
            "By length" => rows.OrderBy(row => row.Text.Length).ToList(),
            _ => rows,
        };

        var limit = options.Count switch
        {
            "First three" => 3,
            "First five" => 5,
            _ => int.MaxValue,
        };

        var shown = rows.Take(limit).ToList();

        var lines = shown
            .Select(row => string.Join(" ", options.Columns.Select(column => column switch
            {
                "Tag" => row.Tag,
                "Length" => row.Text.Length.ToString(),
                _ => row.Text,
            })))
            .ToList();

        return new FilterResult(lines, total, shown.Count);
    }

It does five things in order: split lines, filter by tag, dedupe, sort, limit, and finally join text by the selected columns. Each step looks at only one field of options. Whatever the UI sends, this does; it doesn’t know whether those values were picked in a dropdown or checked in a checkbox group.

The two switch expressions on Sort and Count dispatch on plain strings. This means adding one sort order means changing two places: the choices in the UI and the case here. That is this sample’s trade-off. With only three options, hard-coding is shorter than defining an enum; when options grow, or when they have to line up with an external interface, you should replace them with constants or an enum rather than let business code depend on UI wording.

7.2 Custom Values and Filtering

Two switches, both affecting only “how convenient picking is”, not the type passed back.

With allowCustomValue on, the user can type a new value straight into the box and press Enter to accept it. The sample’s tag dropdown has it on, because a tag that isn’t in the list may turn up in the task list. For example, “Temporary”. Once typed, what gets submitted is "Temporary", no different from picking it from the list.

It does no validation at all. A typo is a value; a string of spaces is a value (unless you filter it yourself). So this switch suits cases where “the list isn’t complete and users may add to it”; if the list is closed, leave it off. Turning it on gives up the guarantee of “only these options”.

filterable defaults to true, meaning as soon as you type in the box, the list below filters by what you typed. With many options this is essential. Thirty tags with no filtering means making people hunt with their eyes. Set it to false and typing won’t filter; the list stays as it is.

The difference between the two is worth stating clearly. filterable only narrows the list; what you select is still an item from the list. allowCustomValue treats the input itself as a value. The first helps you find things faster; the second lets you pick something outside the list. Turn both on and you get “filter by the input first, and if nothing matches, use the input directly”.

The path for a custom value is: open the dropdown, delete what’s already in the box, type the new value, press Enter. If the box already has a value, typing appends to it. To enter a custom value you have to clear it first, or you end up with a strange string made of “old value + new value” joined together. This is the step most likely to go wrong, and the price of doing no validation.

Once the custom value is in, it becomes the component’s current value, on equal footing with the other options. It shows as a small chip, you can click × to remove it, and it won’t appear in the list when you pick again. It isn’t in choices; it is only this one value. To have it there next time too, you have to add it to choices yourself (that takes state, Chapter 14).

Because this value isn’t constrained by the list, the handler function should tidy it up: trim leading and trailing whitespace, limit the length, block obviously invalid characters. The sample does only the lightest step: Where(tag => tag.Length > 0) drops empty strings. Stricter validation (for example, “a tag may be at most four characters”) belongs in the business library alongside the other rules.

When should you turn filterable off? When there are very few options (say three) and the user can take them all in at a glance. Leaving it on isn’t wrong, but one more box you can type in is one more moment of “should I type?”. With three options, opening the dropdown and clicking directly is faster than typing.

filterable is on by default, and you can see it directly in the sample. There are eight tags; only six show when you open it (numChoicesShown: 6). Type a “To” in the box and the list immediately narrows to “To-do” and “To Confirm”. With dozens or hundreds of options, this switch decides whether the user “finds by typing” or “scans with their eyes”.

7.3 Selection Limit and Number of Choices Shown

Two numeric parameters, governing “how many you can pick” and “how many you see at once”.

maxChoices limits how many items you can pick at most. The sample sets it to 3.

Figure 7-4 Three already selected; clicking the fourth does nothing

Click all four in turn. The first three go in; on the fourth, the value doesn’t change. It isn’t added, there’s no message, and the list still collapses. That feedback is weak, and the user may think they misclicked. So when you set maxChoices, it’s best to write a line like “Select at most three” in info so people know in advance.

info is the small line under a component, label the large text above it. In use, label says “what this is” and info says “what limits or caveats there are”. Several components in this chapter deserve an info: the limit from maxChoices, “there’s more” from numChoicesShown, “you can also type your own” from allowCustomValue. It works without one, but writing one removes half the confusion.

numChoicesShown is how many options the dropdown shows at once; the default is 100. The sample has eight tags and sets it to 6, so you see only six when you open it and have to scroll for the other two. The parameter earns its keep with a hundred options or more. Rendering several hundred rows at once makes the dropdown lag; set it to 10 or 20 and let search and scrolling handle the rest.

It doesn’t affect “how many you can pick”, only “how many you see at once”. One parameter governs selection, the other display; don’t mix them up.

maxChoices and allowCustomValue can be used together. When they are, a value typed in counts as an item too. With a limit of three and three already selected, one more custom value won’t go in either. That’s easy to forget. The limit counts “the number of current values”, no matter whether they were picked from the list or typed by hand.

maxChoices belongs only to Dropdown. CheckboxGroup has no such parameter; you can check as many as you like. To limit the count on a checkbox group, you have to handle it yourself: count them in its Change event and, if over the limit, return an Update that removes the item just added. There’s no ready-made parameter for this, and no need to switch components because of it.

numChoicesShown and filterable are a pair. With many options you adjust both. numChoicesShown makes the dropdown shorter, filterable lets people type to find things. Shorten without filtering and the user has to scroll a long list; filter without shortening and the dropdown covers half the screen as soon as it opens.

The default of numChoicesShown is 100. That number is the dropdown’s height, expanded to fit 100 rows, and has nothing to do with a cap on how many are shown. Anything beyond 100 options needs scrolling. With a thousand options, that expanded height covers half the screen, so either turn it down or group the options (Choice itself doesn’t support grouping; you do it by a naming convention, for example “To-do / Today”).

7.4 How Radio and Checkbox Differ in Their Values

Both components look like something you “check”, but one picks one out of a group and the other is a single toggle.

Radio and single-select Dropdown are the same thing: a group of mutually exclusive options of which there can be only one. The only difference is how they look. Dropdown collapses into a box and shows its options only when opened; Radio spreads all the options on the page so you can see them at a glance. With fewer than five options, when you want the user to see them all at once, Radio is the better fit.

        var count = gr.Radio(label: "Count", choices: new[] { new Choice("All"), new Choice("First three"), new Choice("First five") }, value: "All", interactive: true);

It passes a string to the handler function, the same as a single-select dropdown.

Checkbox has no choices; it is simply a toggle.

        var dedupe = gr.Checkbox(label: "Dedupe by content", value: false);

It passes a bool to the handler function. Its value is a Boolean, not a string, which sets it apart from the ones before. The label says “what happens when you check it”, not “what this toggle is called”. “Dedupe by content” is clearer than “Dedupe”, because checking it really does dedupe by content.

What the two share is “neither needs the user to type”; the difference is semantics. Radio is “pick one of these”, Checkbox is “do this one thing or not”. In the sample, “Count” is three mutually exclusive options, so Radio; “Dedupe” is do-or-don’t, so Checkbox. You can force a toggle into a two-option Radio (“Dedupe” / “Don’t dedupe”) and it works, but one extra option is one extra click.

Radio or Single-Select Dropdown

Both components pass a string to the handler function and are identical in capability; which one you pick depends only on how many options there are and whether you want them all visible at a glance.

SituationUseReason
Two to four optionsRadioAll spread on the page; you know what’s there without opening anything
Five or more optionsSingle-select DropdownSpread out, they’d take up half the screen
Options change with another choiceDropdownCollapsed takes less space and won’t jump when options change
Want to see the current choice without openingRadioThe selected dot is filled, the others are hollow

The sample’s “Count” has only three options, so Radio; if one day you add “First ten”, “First twenty”, “All”, “Keep empty lines only”… once options multiply, switch to a dropdown.

How to Arrange a Group of Toggles

The sample’s filter has five controls, two of which are a do-or-don’t toggle (dedupe) and a pick-one single-select (count). When you place them together, the order is worth a thought. Put “pick which” first, then “do or don’t”. The first decides the scope of the result, the second is processing applied to that result; fixing the scope before the processing reads more naturally.

When several Checkboxes sit side by side, write the label like “do this thing”, not as a noun like “Dedupe”. A noun makes people think it’s another option group; only a verb phrase reads as “checking means doing”. The sample writes “Dedupe by content”, and checking it does dedupe by content, with no ambiguity.

Radio’s options are laid out horizontally by default and wrap when they don’t fit on one line. With many options and long names, a horizontal row squeezes into two or three lines and looks worse than a vertical layout. Switching to Dropdown takes less space here. It also has an rtl parameter for right-to-left languages, which left-to-right text like this does not need.

Checkbox differs from the others in one more place: its value is a bool, not a string. So value: false is right and value: "false" won’t compile. This one saves a bit of confusion when reading someone else’s code.

7.5 CheckboxGroup and Select All

CheckboxGroup is “a group of checkboxes you can multi-select”. It looks like Radio (options spread on the page) but lets you pick several.

        var columns = gr.CheckboxGroup(label: "Which columns to show", choices: new[] { new Choice("Tag"), new Choice("Content"), new Choice("Length") },
            value: new[] { "Tag", "Content" }, showSelectAll: true, interactive: true);

Checking and the value correspond exactly. Check “Tag” and a "Tag" appears in the list; uncheck it and one disappears. There is no in-between state of “checked but it didn’t take”, and no “in the value but unchecked in the UI” — unless you return an Update from the handler function that changes the value, which is another matter (Chapter 5).

It passes an object[] to the handler function, the same as the multi-select dropdown in 7.1.

  • Dropdown(multiselect: true) → object[]
  • CheckboxGroup → object[]

Both components are called “multi-select” and pass back the same container. In the sample’s Filter, tags and columns are both declared as object[], so you don’t need two signatures when writing the handler function.

showSelectAll adds a “Select all” box. This box has three states: empty when none are selected; checked when all are selected; and half-selected when some are selected (a horizontal bar, called indeterminate). Half-selected is neither “none” nor “all”; it is the browser’s third state for a checkbox, used specifically to express “some”. Click it once and it goes from half-selected to all; click again and nothing is selected.

The select-all box saves clicks. With three options you can’t see the benefit; with a dozen or so, wanting them all means a dozen clicks.

Two Multi-Selects, One Container

Both multi-select components now come from the same sequence. The component first puts the selected values into an object[]; before calling the handler function, the framework reads the parameter types in the signature and puts those values into the matching container according to the declaration. Declare it as object[] and the values pass through unchanged; declare it as List<object> and the framework creates a new List<object> and moves the values over; declare it as a list interface such as IReadOnlyList<object?>, which both containers implement, and no conversion is needed.

ComponentValue the component givesThe handler function can declare it as
Dropdown(multiselect: true)object[]object[], List<object>, a list interface
CheckboxGroupobject[]object[], List<object>, a list interface

The sample uses object[] for both sets of values. Conversion happens only at the container level. The elements are still object; declaring List<string> or string[] won’t make the framework convert them one by one, and the call reports a type mismatch. To get strings, you still call ToString() yourself as in 7.1.

The difference between an array and a List here comes down to syntax. An array has a fixed length and uses Length; a List can grow and shrink and uses Count. Both have indexing, iteration, and Select. Which one you pick depends on how the business side wants to handle the set of values, not on whether you used a dropdown or a checkbox group.

What Select All Actually Does

Clicking the select-all box doesn’t just check three boxes; it writes all three option values into the component’s value at once. So the handler function receives the full three items, not a “Select all” marker. Clearing select-all is the same: the value goes back to an empty array.

In other words, showSelectAll is just one more box in the UI; it doesn’t change what’s passed back. The handler function doesn’t need to know whether the user checked items one by one or pressed select all; the values are identical either way. A UI convenience doesn’t necessarily leave a trace in the data.

There’s a practical benefit to using select all for “Which columns to show” in the sample. “Tag” and “Content” are checked by default; if the user wants to change to “Length” only, they can either press select all and then uncheck two items, or simply click the two off. The select-all box here acts as “one click back to wanting everything”. With columns, users usually want “show all columns” or “show only one column”, with few in-between states.

7.6 The Shape of choices and type

choices is a Choice list, and each Choice has two things: a value and a label.

new Choice("todo", "To-do")     // the value is todo, displayed as "To-do"
new Choice("todo")              // value and label are both todo, displayed as "todo"

The first form keeps the two separate. What the user sees is a readable label, while the program receives a stable code. This is the most common form. What the UI shows to people and the value the program uses should not be the same thing. The second form supplies only a value, which is both what is displayed and what is passed back; it suits cases where “the value itself is meant to be read” (the tags in the sample are like this — the same text is both value and label).

A Choice’s value doesn’t have to be a string. Give it a number.

new Choice(1, "one")

What the handler function receives is a double 1, not an int 1. As with Number, a number is a JSON number in transit and becomes a double-precision float when read into C#. Cast it in the handler function if you want an integer.

type decides whether the handler function receives the “value” or the “index”. The three components with options (dropdown, radio, checkbox group) all have this parameter and it means the same in each. Single-select passes one; multi-select passes a set.

typePassed to the handler functionValue the option above sends out
"value" (default)The option’s value"todo"
"index"The option’s position in the list (starting from 0)0

Use index when “you don’t care what the value is, only which one was picked”. It has a hidden risk: change the order of the options and every index changes. So unless the options are fixed and their order never moves, use value.

The Two Forms in the Sample

The two dropdowns in 7.1 are exactly the two typical cases.

tags gets its options from an array in the business library, TaskFilter.AllTags, converted with Select into Choices. This form suits cases where “the options are a piece of data”. The list is maintained on the business side and the UI merely draws it. Add a new tag and the UI has it automatically, with no change here.

sort’s options are three hard-coded Choices. This form suits cases where “the options are just a few branches in the code”. The sort orders map to the three cases in the switch; adding or removing one means changing code, so writing them right here is clearest.

Both forms supply only one value; the label of Choice("Source text") is also “Source text”. The name of a sort order is itself meant to be read by people, so there’s no need to invent a separate English code. When should you split them? When the value needs to stay stable and the label needs to be localized. For example, use "by-length" as the value and “By length” as the label. A stable value means interfaces and saved files don’t break when the wording changes; a changeable label means switching languages touches only the label.

Splitting them has another benefit: the value can carry information. For example, give tags values like "todo", "doing", "done", and the business side can tell what state it is at a glance; if the values carried the display wording too, the business code would fill up with string constants and changing one word would mean a global search. UI wording changes; the values in code shouldn’t follow it. Split the two and changing the wording touches only the second argument of Choice.

type: "index" is used rarely, but there is one case where it beats value: when the options are “a list that changes” and you care only about “which position”. For things like “which column” or “which character”, the value is itself a position, so the index is the most direct choice.

Think through its cost in advance. Suppose today’s options are “Source text”, “By tag”, “By length”, and a user saved a 2 (By length). Tomorrow you insert “By date” in the middle and 2 now means “By date”. Same value, different meaning. value has no such problem, because it is a string and doesn’t drift with the order. So use value by default and index only when “position is the meaning”.

type affects only what is passed back, not the value you pass in. The value given at construction is always an option’s value, never an index. This is easy to remember backwards: assume that writing index means giving value: 1, and the constructor throws (Value: 1 is not in the list of choices).

7.7 Empty Values When Nothing Is Selected

The four components behave differently for “nothing selected”.

Single-select Dropdown selects the first item automatically. Give it no value and the box already holds the first item’s value when the page opens, which is also what the handler function receives. In other words, a single-select dropdown has no “empty” state; it always has a value.

Radio is null when you give it no value. With nothing clicked, the handler function gets null. To give it a default you must write value explicitly (the sample’s “Count” writes value: "All").

Both multi-selects are empty arrays. They are “empty collections”, not null. So iterating over them in the handler function won’t throw, but a null check won’t save you.

Put these four differences together and writing a handler function calls for a decision. “Nothing selected” has three representations across the four components (a default value, null, an empty collection). To unify them, convert to one form at the entry of the handler function — for example, turn everything into “empty collection means nothing selected” and treat the single-select dropdown’s default as “the user picked the first item” rather than “nothing selected”.

ComponentWith no valueCan it express “nothing selected”?
Single-select DropdownSelects the first item automaticallyNo
Multi-select DropdownEmpty arrayYes
RadionullYes
CheckboxfalseYes (false means unchecked)
CheckboxGroupEmpty arrayYes

Only the single-select dropdown row is “No”. This decides that for any field where “leaving it unselected is fine”, don’t use a single-select dropdown — unless you’re willing to give it an “Unlimited” option and let “Unlimited” take the first slot. The sample’s “Sort” is just such a field. There always has to be a sort order, so selecting the first item automatically is fine.

One more easy mix-up: an empty string is not “nothing selected”. If an option’s value happens to be an empty string (new Choice("")), selecting it gives the handler function "" — a perfectly valid string value. That is a different thing from the null or empty array of “nothing selected”. When deciding “was anything selected”, use null or the collection’s length, not string.IsNullOrEmpty. The latter also counts “the user picked an empty value” as nothing selected.

This kind of empty-value trap came up in Chapter 3 (a text box gives "", a number box gives null); selection components add one more, the collection. The rule for deciding is still the same one. Work out what “empty” means in the business logic first, then decide which check to use.

The sample’s tag filter is handled exactly this way. An empty array means “don’t filter by tag”, so everything is kept; select some tags and only those are kept. Because a single-select dropdown has no empty state, the sample uses multi-select for tags. Had it used single-select, “don’t filter” would have been impossible to express.

Why Single-Select Dropdown Has No Empty State

The reason is straightforward: a single-select dropdown always has to show something in its box. Leave the box empty and users think it didn’t load; show “Please select” and that is also an option, which needs a corresponding value when selected. So its default behavior is “select the first item”, keeping a real value in the box at all times.

Radio is different. Its options are spread out; when none is clicked, the page makes that perfectly clear — not a single dot is filled. It doesn’t need “select the first item” to avoid ambiguity, so it can stay empty.

Knowing this gives you two choices when using it. Either give it an explicit default so that “doing nothing” still maps to a concrete behavior (the sample’s “Sort” is like this — the “Source text” default keeps the result at least in order), or switch to multi-select so “empty” can be expressed (the sample’s “Tag”).

Radio is the opposite: it is empty by default, so wanting a default means writing it explicitly. The sample’s “Count” writes value: "All" because “no limit” is the most common starting point. One component has a value by default and the other doesn’t; the way you write them is exactly reversed.

One Way to Unify Empty Values

    // Illustration: treat empty as select all
    var picked = tags.Length == 0 ? TaskFilter.AllTags : tags;

This is the “empty means all” form. Select no tags and it’s treated as selecting all; one conditional expression is enough for the whole check. The sample doesn’t have this line; it uses another form. The options.Tags.Count > 0 check in the business library has the same effect: with no tag condition, filtering is skipped.

The other way round, “empty means do nothing” is an early return: no tags selected, return an empty result and don’t compute further. Both are reasonable; which one you pick depends on what it means in the business logic. “Filter” is usually the former (not filtering means wanting everything); “bulk delete” is usually the latter (with nothing selected there’s nothing to delete).

The sample’s business library chose the first form; the code looks like this.

        if (options.Tags.Count > 0)
        {
            rows = rows.Where(row => options.Tags.Contains(row.Tag)).ToList();
        }

“If tags are empty, skip this filtering step.” With no tag condition, all rows are kept. This line can be so light because the UI has already unified “empty” into “empty collection”; if the UI passed null, this would have to check for null first and the code would gain a layer.

A third way to handle it is “empty can’t be submitted”: turn off the button’s Interactive, or have the business layer throw “Select at least one tag”. This fits cases where “you must pick one”; blocking it in the UI up front is friendlier than reporting an error afterwards.

7.8 Chapter Summary

Dropdown’s multiselect decides single- or multi-select: single-select passes string, multi-select passes object[]. allowCustomValue makes the input itself a value (no validation); filterable only narrows the list. maxChoices limits how many you can pick (extra clicks do nothing, with no message); numChoicesShown limits how many you see at once.

Radio is the same as a single-select dropdown: it passes string and is null when nothing is selected. Checkbox is a toggle: it passes bool and defaults to false. CheckboxGroup can multi-select: it passes object[], and showSelectAll gives it a select-all box that can be half-selected.

Each item in choices is a Choice: you can give only a value (it is both displayed and passed back), or give the value and label separately (the label is shown to people, the value goes to the program). Numeric options pass a double. type: "index" passes an index, and all of them change as soon as the order does.

“Nothing selected” has three representations across the four components: the single-select dropdown picks the first item automatically, Radio is null, and the two multi-selects are empty arrays. Unify them in the handler function before going any further.

One Table to Decide Which to Use

Put this chapter’s four components together and choosing one takes three steps.

What you want to doUsePasses back
Pick one from a long listSingle-select Dropdownstring
Pick several from a long listDropdown(multiselect: true)object[]
Pick one from three or five, all visible at a glanceRadiostring
Pick several from three or five, all visible at a glanceCheckboxGroupobject[]
One thing, do it or don’tCheckboxbool

“A long list” and “three or five” have no hard rule; it depends on what fits on the page. A Radio with five options takes one line, with ten it takes two, and then a dropdown fits better. The same question works in reverse too. A dropdown with three options takes one more click to see them all, so a spread-out Radio is better.

The sample’s filter module uses only five controls yet puts all four components to work: multi-select dropdown (tags), single-select dropdown (sort), radio buttons (count), checkbox group (columns), toggle (dedupe). What it does is simple (filter once by conditions), but it lays out exactly the differences this chapter is about.

Only one thing is new in this chapter: the container type. The components in the first six chapters all passed single values to the handler function; here two components pass a set of values, both object[]. Declaring List<object> works too — the framework swaps the container to match the declaration before the call; the elements are still object, so you convert them yourself if you want strings. The rest repeats the contract from Chapter 3: parameters line up by position, and a type mismatch is an error.

The next chapter switches to a batch of read-only components. They take no input; they only present the result properly. Tables, charts, chats, images — each has its own way of presenting.

Chapter 8. Display Components

Every component in the first seven chapters takes input: text boxes take text, dropdowns take options, sliders take numbers. This chapter switches to a different kind, drawing only, taking nothing.

The workbench needs such things too. When a filter finishes, the result is a pile of data; dumping it into a read-only text box is readable but not good-looking. A score should be drawn as a bar, a structure should be collapsible, tagged source text should have color, a piece of explanation should have a heading and a list, and a conclusion should be wrapped in a card.

Figure 8-1 Five display components, five kinds of content

The sample adds a fourth block to the shell, the display area. It reads the filter result and presents it once in each of five ways.

Figure 8-2 The display area, five slots each holding one block

Click “Render” and all five blocks fill with content at once.

Figure 8-3 After rendering: report, raw data, tag distribution, annotation, card

The five blocks from top to bottom map exactly onto the five components. This chapter goes through each one’s quirks. Every one has at least one place where “writing it any other way breaks it”.

The display area takes two inputs, the raw items and the filtered result. The report has to state “how many in total, how many left”; the denominator has to be counted from the raw items and the numerator from the filtered result, so one input can’t supply both numbers. The five components share these two sets of data, each taking the part it needs. Label only counts tags, HighlightedText only splits lines, and JSON only holds a few summary fields.

Markdown is the most used one and the easiest to underestimate. It takes a string and draws it as headings, lists, bold text, links, and code blocks according to Markdown syntax.

            var report = gr.Markdown("Not rendered yet.", label: "Report");

The sample’s report is assembled dynamically.

    var formula = $"$$\\frac{{{kept.Length}}}{{{total}}}$$";
    var top = counts.OrderByDescending(pair => (double)pair.Value).First().Key;

    var report = $"""
        ### This Filter

        There are **{total}** items in total, **{kept.Length}** left after filtering, retention rate {formula} ({ratio:P0}).

        - Tag types: {counts.Count}
        - Highest share: {top}
        """;

Whatever you write in the string is what appears on the page. Headings, bold, lists — all follow the syntax. That is one way it beats a read-only text box. With the same piece of text, adding ** makes it bold and adding - makes it a list, with no HTML to assemble.

The {ratio:P0} in the report writes 0.375 as 38%. P is the percent format and 0 is the number of decimal places. Don’t multiply by 100 again in the interpolation expression — P has already done that, and you’d get 3750%. How a number displays is decided by string interpolation; the formula only handles layout.

Here are the common ones, run through once.

SyntaxRenders as
# Heading, ## SubheadingLevel-one and level-two headings (more # means smaller)
**bold**, *italic*Bold, italic
- one itemUnordered list (1. is an ordered list)
> a paragraphBlock quote, with a vertical line on the left
`code`Inline monospace
Wrapped in three backticksCode block, with an optional language
[text](address)Link
![caption](address)Image
Several lines separated by vertical barsTable

This list is enough to draw most results. What it can’t cover is “precise layout”. Column widths, spacing, rounded corners, hover effects — Markdown syntax can’t express those.

One practical suggestion. For report-style content, use the three-part form of “heading + a paragraph + a list”. The heading says what it is, the paragraph gives the conclusion, the list gives the details. It reads better than one long stretch of text and is easier to write than a pile of tables.

Heading levels have to line up with the page structure. The sample’s page header uses # for the site name, the four blocks’ subheadings use ###, and the report’s subheading also uses ###. There should be only one # on a page; use # everywhere and every block is as large as the page header, so the hierarchy is gone.

Tables have one hard requirement: the separator row can’t be omitted. Write only a header and a few data rows and it won’t render as a table, just as a paragraph of text with vertical bars. The separator row’s column count also has to match the data; one column short and the later columns are dropped.

Nested lists rely on indentation: a child item gets two more spaces than its parent. Not enough indentation and the child is treated as a sibling.

Formulas

There are two easy mistakes with formulas, both about delimiters.

By default only $$...$$ is recognized. Write $E = mc^2$ and the page shows those characters verbatim instead of rendering a formula. For inline formulas you have to state explicitly what the delimiters are.

gr.Markdown("Inline $E = mc^2$", latexDelimiters: new[] { new LatexDelimiter("$", "$", false) });

LatexDelimiter has three parameters: the left delimiter, the right delimiter, and whether it is block-level (display). false means inline, with the formula on the same line as the text; true means block-level, with the formula on its own line, centered and in a larger font. The sample uses block-level $$...$$, so the retention-rate fraction is shown on a line of its own.

Why isn’t $ recognized by default? Because $ is too common in ordinary text: amounts, variable names, command prompts all contain it. Recognizing only $$ by default trades “recognizing a little less” for “no false positives”. If you really want inline formulas, declare the delimiters once, and from then on every $...$ in that component is treated as a formula.

Don’t write % inside a block-level formula. LaTeX treats % as a comment marker, so 100% renders as just 100. That’s why the sample puts the percentage outside the formula (“retention rate [fraction] (100%)”) and leaves only the fraction inside. This one is subtle: the code is right, the rendering is right, and a single character is simply missing.

With headerLinks on, each heading gets a link icon in front of it that appears only on hover; clicking it makes the address bar jump to #h-heading-text. It suits long documents. With a dozen or so subsections on a page, giving each one a copyable address is useful.

gr.Markdown("# A heading with a link", headerLinks: true);

It only means something when there are headings. For a stretch of text with no #, on or off makes no difference.

What It’s Not For

Markdown isn’t for “precise layout control”. It can make text look good, but you can’t say “this box is 300 pixels wide, with 12 pixels of left padding and 4-pixel rounded corners”. For that kind of control, use Html.

It’s also not for drawing structured data. An object written out in Markdown is just a lump of text, while JSON can collapse it and show the hierarchy.

8.2 Markdown’s HTML Sanitizing and Height

Markdown lets you mix HTML into the text, which raises a question: where does that HTML come from?

If you wrote all of it yourself, no problem. If any of it is user input (say you splice a user-supplied title into a report), there’s a risk. A user puts an image with onerror in the title and that script runs when the image fails to load; put in an <iframe> and the page gains a chunk of content from somewhere else.

sanitizeHtml is what handles this; it defaults to true.

TagSanitizing on (default)Sanitizing off
<b>, <i>KeptKept
<span style="color:red">KeptKept
<img src onerror>Tag kept, event attribute removedAll kept
<iframe>RemovedKept
<div onclick>Tag kept, onclick removedAll kept
<script>RemovedKept

This table leads to one conclusion. What it blocks is “things that execute”, not “all HTML”. Bold, color, images — things that only affect display — stay; scripts, embedded pages, event attributes — things that can run code — are removed.

Turning it off (sanitizeHtml: false) means all of the above is output exactly as written. When should you turn it off? When the HTML is generated entirely by your code and you genuinely need things like <iframe> that get stripped. If there’s even a trace of user input in the content, don’t turn it off.

Be precise about what happens after you turn it off. A <script> tag stays on the page, but browsers don’t execute scripts inserted via innerHTML; event attributes like onerror do execute instead. So with sanitizing off, the worry about someone slipping in a script is smaller than you’d think — what you actually have to guard against is an image with onerror. Judge the risk by whether an event is attached, not by the tag name.

When does this come up? The most common case is splicing user input into Markdown. The sample’s report has no user input, so leaving sanitizing on changes nothing. But if the report contains a line like “Result name. {name}” and name is user-supplied, a user typing <img src=x onerror=...> puts that straight into the page’s HTML. With sanitizing on, onerror is removed; with it off, it stays on the page and the script runs as soon as the image fails.

The boundary needs stating clearly here. Sanitizing reduces risk; it isn’t a security guarantee. It filters tags and attributes against a list, and anything outside that list, differences in how browsers parse, and combined bypass tricks are all outside what it promises. To really render untrusted content onto a page, you have to handle it on the server first. That’s a web-security topic, not something a component parameter can solve.

So the right attitude has two layers. Keep user input out of HTML where you can (for example, escape a title to plain text before splicing it in), and only when you really must let it in, fall back on sanitizing — while knowing it doesn’t cover every case.

One more easy-to-miss point. Markdown’s sanitizing applies only to HTML fragments, not to Markdown syntax itself. A link like [click me](javascript:alert(1)) written by a user doesn’t go through the HTML path. Validating link targets belongs in the business layer. That’s the division of labor between “sanitizing” and “validation”: the former handles tags, the latter handles content.

Line Breaks and Height

lineBreaks handles line breaks. It defaults to false, with Markdown following the standard syntax: a single newline is merged into a space, and you need a blank line to start a paragraph. Set it to true and a single newline becomes a <br>.

When do you need it? For text pasted in from elsewhere — say a list arranged line by line with none of Markdown’s blank lines. Default rendering squeezes it into one paragraph; with lineBreaks on, the lines stay separate.

There are three height parameters: height, maxHeight, minHeight. height is a fixed height, scrolling when content overflows; maxHeight is “grow at most this tall”, and the box shrinks when there’s less content; minHeight is the reverse. Give none of them and the height follows the content.

How to pick depends on whether the content can grow.

ContentUseReason
A fixed few lines of stable lengthNone of themThe box follows the content, no more and no less
Reports, logs, varying lengthmaxHeightShort content doesn’t take up space; long content doesn’t push what’s below away
A fixed-size panelheightPosition doesn’t jump; overflow scrolls

The price of a fixed height is blank space when content is short and a scrollbar when it’s long. For a stable layout that price is worth paying; if you’re only worried about content getting too long, use maxHeight.

To confirm sanitizing really does something, put an <iframe> into a piece of Markdown and it won’t be on the page; put onclick into a <div> and clicking does nothing. Turn sanitizeHtml off and look again, and both stay on the page. Judgments like this have a direct way to be checked: change one parameter and compare whether those two things are on the page.

What You Can Embed

What sanitizing blocks are things that execute (scripts, event attributes, inline frames); layout tags and inline styles aren’t affected. There’s still plenty you can use for layout. Three common ones.

Collapsing. Use <details> and <summary> to fold long content away, visible only when clicked open.

gr.Markdown("<details><summary>Expand for details</summary>\n\nContent inside the fold.\n\n</details>");

Attaching a stretch of raw data or a log to a report — both suit folding. The main text stays short, and anyone who needs to check opens it themselves.

Small blocks side by side. Markdown syntax has no “horizontal arrangement”; use a div with flex.

gr.Markdown("<div style=\"display:flex;gap:8px\"><span style=\"padding:2px 8px;background:#eef2ff;border-radius:10px\">Badge one</span><span style=\"padding:2px 8px;background:#eef2ff;border-radius:10px\">Badge two</span></div>");

For things like badges and status labels, this looks better than a string of **.

Native tables. Markdown’s table syntax can’t express merged cells; when you need them, write a <table> directly.

All three stay on the page, which means they aren’t on the list. What the list blocks are <script>, <iframe>, and on* attributes. There’s just one criterion: will this HTML execute code?

8.3 Html: Template Substitution and Default Styles

Html sits one level below Markdown: it outputs HTML directly. Two parameters decide what it outputs. value is the data, htmlTemplate is the template, and ${value} in the template is replaced by the data.

            var card = gr.HTML("Not rendered yet.", label: "Card",
                htmlTemplate: "<div style=\"padding:12px;border-left:4px solid #3366cc;background:#f6f7f9\">Kept <b>${value}</b></div>");

This template wraps value in a light-colored block with a left border. The handler function returns "8 items (out of 8)", and that sentence appears wrapped in the box on the page (the bottom block in Figure 8-3).

The default of htmlTemplate is ${value}. In other words, if you don’t write a template, value itself is output directly as HTML. The sample’s template adds a layer of wrapping, so the data (a plain-text sentence) and the layout (that bordered div) are separated. Changing the layout doesn’t touch the handler function, and changing the data doesn’t touch the template.

The template replaces only this one placeholder, ${value}. Names like ${color} or ${title} aren’t replaced with anything. They don’t exist in the template’s scope, the whole block errors out, and all that’s left on the page is a line reading Error rendering HTML: color is not defined. To pass several values, assemble them into one HTML string in the handler function and write the whole thing into value.

That’s the path the sample’s card takes. The template only handles the border; the content is assembled by the handler function.

    var card = $"{kept.Length} items (out of {total})";

The <b>${value}</b> in the template thus becomes “Kept 8 items (out of 8)”. The bold comes from the template, the numbers from the handler function. If you later want to add an “updated at” time, you change only that one line in the handler function and not a word of the template. Data belongs to data and layout to layout; that’s the only value of the template parameter.

It Doesn’t Sanitize

Markdown has a layer of sanitizing; Html doesn’t. Whatever you write in value goes into the page as-is.

No need to guess at this; two lines show it. Put onerror on an image and that script still runs when the image fails to load; write an <iframe> and it’s embedded in the page, border styles and all. Both get through.

So Html’s boundary sits further out than Markdown’s, and the risk is greater too. If even one character in the content comes from a user, you have to escape it yourself.

var safe = System.Net.WebUtility.HtmlEncode(title);
var card = $"<b>{safe}</b>";

HtmlEncode turns <, >, &, and quotes into entities, so the browser shows them as text instead of structure. No component covers this step for you; whoever assembles the string is responsible for escaping it.

applyDefaultCss defaults to true and adds a basic set of styles (font size, spacing, margins) to tags like h1–h6, p, ul, table, so bare HTML doesn’t look bad. Set it to false and the styling comes entirely from your own HTML — use that when you want to control layout from scratch — at the cost of headings, paragraphs, and lists all falling back to browser defaults, with line height and spacing yours to write again.

A middle-ground use: keep the default globally and override it with inline styles only on the section that needs special layout. The sample’s card does exactly that — applyDefaultCss is left alone, and the style in the template makes that left border.

Html’s typical uses are all cases where “the layout is itself the content”: cards with a left border, status badges, progress bars, embedded players. You can’t write those in Markdown; with Html they’re a few lines of string.

How to choose between Html and Markdown? Look at the content itself. If the content contains formatting syntax (Markdown), use Markdown; if it’s a piece of HTML whose layout you need to control precisely, use Html. Using them the other way round is awkward. Put Markdown syntax into Html and it won’t render — the page shows the asterisks and hash marks verbatim; push a large chunk of HTML into Markdown and <iframe>, on*, and the like get stripped by sanitizing.

8.4 Html: Load Scripts

Html has one more parameter, jsOnLoad, which runs a piece of JS after the component loads. Its default is a single line.

element.addEventListener('click', function() { trigger('click') });

It means “click this block and its click event fires”. That’s what lets Html bind Click (Chapter 5). Set it to null or an empty string and the block is just a static block: even with Click bound, nothing fires.

The element in the script is the container holding the template content, not the whole component’s frame. The sample’s card doesn’t set jsOnLoad, so it gets that default line, which means that besides displaying, it could also bind Click; the sample doesn’t bind it, so clicking does nothing.

When you write your own, element works the same way — for example, to make some spot in the block show something the script computed.

gr.HTML("Original text", htmlTemplate: "<div class=\"w\">${value}</div>",
    jsOnLoad: "element.querySelector('.w').textContent = 'Changed by script'");

What the page shows is “Changed by script”, not “Original text”. The script runs after the template renders and changes the content.

It runs only once, at mount time. Afterwards, when the handler function updates value and the template substitutes again, the script doesn’t rerun. Wire that block up to a button, click once to swap in a new value, and the display goes back to the new sentence — the content the script changed is gone. If you want “every piece of data to pass through the script”, this parameter can’t do it. It executes once at mount, and the template takes over from there.

This parameter suits “small widgets”. A piece of HTML that needs initialization before it works (a chart library, a map, a player) can have its init function called in jsOnLoad. The code you write runs in the browser, so only put your own code in it — don’t splice in user input. That’s the same line as escaping in the previous section: whatever you put in must either be trusted or processed first.

There’s also a head parameter that puts content into the page’s <head>. Use it to pull in an external script or stylesheet. It affects the whole page, not this one component. Write a <style> in there and every element on the page matching the selector is affected, including other components. Know that you’re changing globals when you use it, and keep selectors as narrow as possible.

gr.HTML("<p class=\"hh\">Look at the color</p>", head: "<style>.hh { color: #c00; }</style>");

That <style> really does go into <head>, but the color has no effect. The component’s own paragraph-color rule has higher priority; you need !important to override it.

head: "<style>.hh { color: #c00 !important; }</style>"

The benefit is not having to cram styles into value; the cost is that the class name becomes global, the component’s own rules still sit on top of it, and you have to think about priority when writing styles.

8.5 JSON: Collapsing and Height

JSON takes an object and draws it as a structure with line numbers that can be collapsed.

            var data = gr.JSON(null, height: 220, label: "Raw data");

The sample’s handler function returns an anonymous object, and the page shows its structure.

    var data = new
    {
        total,
        kept = kept.Length,
        ratio = Math.Round(ratio, 3),
        tags = counts.Keys.ToArray(),
    };

open controls the initial expansion. By default it expands to the third level; deeper levels collapse to a single line Object(n) that you click to see. Set it to true and everything expands. Don’t expand everything when the data is deeply nested — a screen full of braces hides the structure instead of showing it.

The sample gives it an anonymous data object with no defined type. Fed to this one component, it can be drawn from the structure of property names and values; JSON doesn’t read type names. If that data also has to go elsewhere (say to Label at the same time), define a record instead of assembling it twice in two places — assemble it twice and sooner or later the two won’t match.

showIndices adds indices to array elements. When objects in an array all look alike, only an index tells you which one you’re looking at. It does this by turning elements into keyed items: [1, 2] displays as two lines, "0": 1 and "1": 2, with the index as the key. Quotes on keys are a JSON rule; keys can only be strings, so don’t mistake them for fields of the data itself when reading.

height and maxHeight work the same as in Markdown. JSON especially needs them: a slightly complex object runs to dozens of lines, and without a height limit it pushes the whole page down. The sample gives height: 220, and the overflow scrolls.

The sample’s value starts as null, so the page shows an empty box. That’s more honest than stuffing in fake data: an empty box says plainly “no data yet”, while fake data makes people think it’s the result.

What is JSON for? Debugging and checking. Whether the structure returned by the handler function is right, whether a field name is misspelled, whether an array is empty, whether a number got rounded down to 0. You can’t see those in assembled text; in a structure they’re separate fields.

Then from Chapter 5 has a handy use here. The main step gives the user the finished result; in Then you give the same batch of raw data to a JSON. The user sees the result, you see the data, and the two don’t get in each other’s way. When it actually ships, delete that JSON from Then.

The other way round, JSON isn’t for end users. A screen of braces is something no one but a developer wants to read; if you really need to show users a structure, rearrange it with a Markdown table or list.

8.6 Label: Presenting Classification Scores

Label takes a set of “tag → confidence” pairs and draws them as percentage bars. It was originally made for classification models: a model outputs a bunch of probabilities, and this component shows the highest one enlarged, with the rest arranged as bars in proportion.

            var distribution = gr.Label(null, label: "Tag distribution");

The sample uses it to show the tag distribution.

    var counts = all.Lines
        .Select(line => line.Split(' ')[0])
        .GroupBy(tag => tag)
        .OrderByDescending(group => group.Count())
        .ToDictionary(group => group.Key, group => (object)Math.Round((double)group.Count() / all.Shown, 3));

There’s one detail you have to know here. The dictionary’s value type must be object, not double. Write new Dictionary<string, double> and it throws at runtime.

System.ArgumentException: The Label output expects one of: a string label, an int label,
a float label, or a dictionary whose keys are labels and values are confidences;
got a System.Collections.Generic.Dictionary`2[System.String,System.Double].

The message says it accepts “a dictionary whose keys are labels and values are confidences”, but it doesn’t recognize the specific type you gave. Switch to Dictionary<string, object> and it passes. The values are still double; only the container’s generic parameter differs. This is this chapter’s first case of “the type looks right but isn’t”.

Values are rendered as percentages, with 0.25 shown as 25%. So what you pass in should be proportions, not raw counts — the sample divides by the total first. Pass counts in and you get absurd numbers: a category with 2 items, passed straight as 2, shows as 200% on the page.

The denominator has to be picked correctly too. The sample uses all.Shown (the total before filtering), not the count after filtering. This block shows “how much each tag accounts for in all the data”, so all the data is naturally the denominator. If you want “how much each tag accounts for in the filtered result”, change the denominator to the post-filter count. The two sentences sound almost the same, but the numbers on the chart differ a lot.

You also have to decide how many decimal places to keep. The sample uses Math.Round(..., 3), and 0.125 passed in displays as 13%. Percentages show as integers, so decimals aren’t visible. Three decimal places is already finer than the display precision; going finer is pointless. The length of a bar can only ever give a rough idea anyway.

numTopClasses limits how many items are shown. By default all are shown; set it to 2 and only the top two remain, with the rest not drawn. Use it when there are many tag types and you only want people to see the top ones.

showHeading defaults to true and shows the highest item enlarged on its own at the top. If the highest item doesn’t matter, or you’ve already explained it in a heading, set it to false and keep only the bars.

color changes the background of that enlarged block at the top, using a hex color value. The bars themselves follow the theme and aren’t affected.

When should you use it? When a set of numbers needs “who’s bigger at a glance”. The same five tag counts written as a Markdown table are five rows of numbers the reader has to compare mentally; drawn as bars, the longest one is given by its length, with no need to compare numbers one by one. It isn’t for precise reading: 25% and 24% are almost the same length on the chart, so pair it with a table if you need exact values.

Label isn’t limited to classification models either. Any “set of named proportions” (tag distribution, share of error types, time spent at each stage) can go here. What it wants is proportions, not the status of being “a classification”.

Besides a dictionary, it also accepts a single string or a single integer; then the page has only one label and no bars to arrange.

8.7 HighlightedText: Segments and Legend

HighlightedText takes a series of “text + category” segments, colors each segment by its category, and joins them into one continuous stretch of source text.

            var marked = gr.HighlightedText(null, showLegend: true, label: "Annotation",
                colorMap: new Dictionary<string, string>
                {
                    ["To-do"] = "#c2410c",
                    ["In Progress"] = "#1d4ed8",
                    ["Done"] = "#15803d",
                    ["To Confirm"] = "#7c3aed",
                    ["Archived"] = "#6b7280",
                });

The sample splits each filtered line into two segments, one for the tag and one for the content.

    var tokens = kept
        .SelectMany(line =>
        {
            var space = line.IndexOf(' ');
            var tag = space < 0 ? line : line[..space];
            var rest = space < 0 ? "" : line[space..];
            return new[] { new HighlightedToken(tag, tag), new HighlightedToken(rest + "\n", null) };
        })
        .ToArray();

There’s one more type requirement here: segments have to be HighlightedToken. Pass a tuple array directly, writing new[] { ("To-do", "todo") }, and it throws.

System.ArgumentException: A highlighted text is made of tokens, pairs, or a text with its entities;
it was handed a System.ValueTuple`2[System.String,System.String][].

HighlightedToken has two parameters: the text and the category. A segment whose category is null isn’t colored (in the sample the content segment is null, so only the tags get color).

That code does one thing: it splits each line at the first space, with the tag in front and the content behind. Splitting the tag out is so it can be colored. Treat the whole line as one segment and the color covers the entire line, so readers can’t tell which part is the tag. SelectMany here flattens “two segments per line” into one big array; Select would give an array of arrays, which the component doesn’t accept.

This splitting has a precondition: the first column of the filtered result is the tag. The sample’s “Which columns to show” has “Tag” checked by default, so it holds; uncheck that column and the first word of the content gets colored as a tag. Display components accept strings, and what format those strings carry has to be agreed on between upstream and downstream.

colorMap assigns a color to each category: the key is the category name, the value the color.

gr.HighlightedText(tokens, colorMap: new Dictionary<string, string> { ["To-do"] = "#c2410c" });

Leave it out and a default palette is used. The defaults are distinct enough, but may not match your theme. The sample gives each of the five tags its own color, and in Figure 8-3 the legend’s color swatches line up one-to-one with the colors in the text.

One thing to note when setting it: what the legend shows is the category name itself. Write category names like “todo” or “in-progress” and those are exactly the words in the legend, so the reader has to translate them first. The sample uses the tag names directly as category names (new HighlightedToken(tag, tag)), so the legend and the text match, with no guessing.

showLegend decides whether the legend is drawn. With it on, category names are listed above the text (the row of colored squares in Figure 8-3); with it off, the category name travels with each segment (showInlineCategory, true by default). Both are ways of “letting people know what a color means”; the difference is one is concentrated and the other spread out. Use a legend when there are many categories; inline saves space with two or three.

combineAdjacent merges adjacent segments of the same category into one, separated by adjacentSeparator. A tokenizer often outputs one word per segment; when adjacent words share a category, merging them reads more smoothly.

One more thing: you have to put the line breaks in yourself. A segment breaks only if it contains \n; without it, everything runs on in one line. The sample appends \n to each line’s content segment, so the eight tasks each take one line; remove it and the eight lines collapse into a single paragraph.

showWhitespaces defaults to true and keeps the whitespace before and after a segment. Segments from a tokenizer often carry spaces; turn it off and each segment is trimmed, so the spaces are gone. Text without spaces has no use for it; splitting English words does.

What is HighlightedText for? Source text with annotations. Named-entity recognition marking people and places, tokenization results marking parts of speech, a proofreading tool flagging suspect segments. What they share is “the source text can’t change; only some segments are tagged”. It isn’t for showing classification statistics (that’s Label’s job), nor for long documents (it has no notion of headings or paragraphs).

8.8 Updating Five Components at Once

The sample’s “Render” button updates all five blocks at once. The binding is written as in Chapter 5; here we only look at how it relates to the display components.

    show.Run.Click(Render,
        [filter.Items, filtered.Lines],
        [shown.Report, shown.Data, shown.Distribution, shown.Marked, shown.Card],
        apiName: "Render");

The handler function returns five values, in the same order as the line above.

    return (report, data, counts, tokens, card);

The order of the return values is the order of the outputs. The first goes to Report, the second to Data, and so on. That contract was covered in Chapter 3. Getting the order wrong doesn’t necessarily error (report and card are both strings, so swapping them still runs); a wrong type is what throws at runtime (giving tokens to Label).

Five-to-five is easy to misalign, so the sample puts the five components into a record (ShowView), lists them by field order when binding, and changes both sides together so your eyes can line them up.

There’s one more trade-off. The five values have different types, so the return is written as (object, object, object, object, object). They’re all reference types to begin with, so converting to object copies no data; the price is that type checking moves to runtime, and a mismatch in order or type only shows up as an error at runtime. What you get in exchange is “one click updates the whole display area together”. Splitting it into several events, each handling one or two components, also works, but then one click sends several requests. For a display area where “changing together is what makes sense”, one update is the better deal.

If any one of the five outputs errors, the whole event fails. The rule from Chapter 5 holds here too: if the handler function throws, none of the five components update and the UI shows only one error. So the lines that assemble the data have to be solid. A zero denominator, an empty array, a missing field — all blocked inside the handler function. The sample’s total == 0 ? 0 : ... is exactly the move that guards the denominator; without it, an empty item list produces something that isn’t a percentage.

8.9 How to Choose Among the Five Components

All five components can “display”; choosing wrong throws no error, it just feels off. The order of decision: first look at what the content is, then at whether you need precise layout.

ContentComponentKey parameters
Formatted text, reports, explanationsMarkdownlatexDelimiters, headerLinks, lineBreaks
A piece of HTML whose layout you need to control preciselyHtmlhtmlTemplate, applyDefaultCss, jsOnLoad
An object, a batch of raw dataJSONopen, showIndices, height
A set of named proportionsLabelnumTopClasses, showHeading, color
Source text that can’t change, with only some parts taggedHighlightedTextcolorMap, showLegend, combineAdjacent

A few pairs that are easy to confuse, taken separately.

Markdown and Html. The difference isn’t which is more powerful, it’s “who controls the layout”. In Markdown, layout is decided by syntax: ** gives you bold, but you can’t write “300 pixels wide, 12 pixels on the left”. In Html, you decide the layout — whatever you write is what you get. So when content leads and layout follows, use Markdown; when layout is itself the requirement (cards, badges, bordered quote blocks), use Html.

JSON and Label. One shows developers the structure, the other shows users the proportions. For the same batch of data, JSON holds total, ratio, and the tags array, while Label holds five bars of differing lengths. Who it’s for decides which one to use.

HighlightedText and Markdown. Both are “a stretch of text”; the difference is that the former’s every segment carries a category and can be colored or given a legend, while the latter’s text is one whole block with only syntax-level emphasis like bold and italic. For information about “what this segment is”, use HighlightedText; to just bold a few words, use Markdown.

The last point is about direction: don’t use input components for read-only things. A Textbox from Chapter 6 set to interactive: false can display text too, but it carries the shell of an input box and focus styling, so readers think they can edit there. Display is display — use this chapter’s five components. The result areas of the first three modules in the sample are still read-only text boxes. That’s how Chapters 4 through 7 wrote them; this chapter doesn’t go back and change them, and the newly added display area uses this chapter’s components.

For layout, the sample puts the display area in the wider right column (scale: 2), wraps the five components in a Group (covered in Chapter 4; Group adds a border around a set of components), and stacks them top to bottom, each with its label. No Row is used. Each block of content should fill the width; side by side they’d be squeezed into a strip.

The order matters too. The report is at the top (the conclusion comes first), raw data next (look down when you need to check), then proportions, annotation, and card. A reader scanning downward goes from conclusion to detail.

When you look at this table, first ask “what does the reader want to do with this block” — read text, compare sizes, see structure, or see which segment is tagged. Once that’s answered, the component is decided.

8.10 Chapter Summary

None of the five components collects user input; they only draw. Which one you pick depends on the content itself: Markdown for text, Html for precise layout, JSON for structured data, Label for proportions, HighlightedText for annotated source text.

Markdown recognizes only block-level $$...$$ formulas by default; inline formulas need latexDelimiters stated explicitly. A % inside a formula is treated by LaTeX as a comment, so write percentages outside the formula. headerLinks adds anchors to headings. lineBreaks turns a single newline into <br>, which text pasted in from elsewhere needs.

sanitizeHtml is on by default and blocks “things that execute”. Scripts, embedded pages, and event attributes are removed; bold, color, and images stay. It reduces risk, it isn’t a security guarantee — don’t turn it off when there’s user input.

Html substitutes ${value} in htmlTemplate and recognizes only that one placeholder; to pass several values, assemble them into one string in the handler function. applyDefaultCss gives bare tags a basic set of styles; jsOnLoad runs JS once at mount, and the default line makes the block clickable, while later updates to value don’t rerun it. Html doesn’t sanitize. onerror still runs, <iframe> still embeds, so if the content contains user input you have to HtmlEncode it yourself.

JSON’s open controls the initial expansion, showIndices turns array elements into keys like "0" and "1", and height limits the height. A large object has to have a height limit. It’s a debugging tool, not a display for people.

Label’s dictionary value type must be object; pass proportions, not counts, and pick the denominator correctly. numTopClasses limits the number of bars, showHeading controls that enlarged label at the top.

HighlightedText’s segments are HighlightedToken, not tuples; put \n in the segments yourself for line breaks. showLegend and showInlineCategory are the two ways of drawing a legend, and the legend shows the category name verbatim; combineAdjacent merges adjacent segments of the same category.

This chapter has two cases of “the type looks right but isn’t”: Label’s dictionary and HighlightedText’s segments. They’re an extension of the same contract from Chapter 3. The component decides what types it accepts; get it wrong and it fails at runtime, with only “Error” on the UI.

The next chapter is about tables. One component holding dozens of rows and dozens of columns, and editable too.

Chapter 9. Dataframe and Table Interaction

The components in the first eight chapters all accept “a single value” — a string, a number, an option, or a time. The component in this chapter accepts “a whole table”.

The workbench happens to have a table. A task table is column-shaped data to begin with: Tag, Content, Character count, Due, Done. Earlier chapters flattened it into a single stretch of text (one “Tag Content” per line); filtering cut that text line by line, and display split that text line by line. Flattening to text has the virtue of being simple — one Textbox holds it all — but the user can’t edit a single cell directly, and can’t see at a glance which columns there are.

This chapter spreads it back out into a table. Once it’s spread back, everything the earlier chapters did is still here. Filtering still filters by tag, display still draws the result in five ways. The only thing that changes is “what the task table looks like”: from a stretch of text into a table you can view, search, and edit.

Figure 9-1 The table area: one editable table, one read-only comparison table, three callback panels

The sample adds a fifth block to the shell. Three buttons on the left, two tables and three panels on the right, three comparison tables at the bottom. The two tables have identical columns, with exactly one difference: the top one can be edited, the bottom one can’t. The three panels are this chapter’s callback bench — they show “change something, and what does the server receive”. The three comparison tables at the bottom are teaching scaffolding; delete the whole block once you’re done, and the workbench itself is unaffected.

This chapter follows “first understand it, then be able to edit it, finally be able to get it”: how rows, columns, and headers line up, how datatype sets column semantics, how interactive toggles editing, how width and wrapping are arranged, how search is used, what each of the three events brings back, and whether empty tables and row/column counts can actually be capped.

9.1 Dataframe Rows, Columns, and Headers

Dataframe’s value is two-dimensional: a list of rows, and each row is itself a list of cells.

            var grid = gr.Dataframe(
                value: TaskTable.Cells(TaskTable.FromLines(SampleTasks.Split('\n'))),
                headers: TaskTable.Headers,
                datatype: new[] { "str", "str", "number", "date", "bool" },
                columnWidths: new object?[] { 80, 240, 70, 220, 90 },
                interactive: true,
                showRowNumbers: true,
                showSearch: "search",
                label: "Editable table");

The first line, the value chain, has three layers. SampleTasks is eight lines of text; FromLines turns it into eight TableRows; Cells then flattens each TableRow into five cells. The flattened type is IReadOnlyList<IReadOnlyList<object?>>. The outer layer is rows, the inner layer is columns. Eight rows, five columns — eight lists of length five.

Why flatten to object?? Because the five cells in a row aren’t the same kind of thing. The tag is a string, the character count an integer, the due date a date, done a Boolean. The contract from Chapter 3 still holds here: a component accepts one value, and that value itself can have any structure. object? is their common parent type; once Dataframe receives it, it interprets the columns one by one according to datatype.

The flattening code is a single line, in core.

    public static IReadOnlyList<IReadOnlyList<object?>> Cells(IEnumerable<TableRow> rows) =>
    [
        .. rows.Select(row => (IReadOnlyList<object?>)
            [row.Tag, row.Text, row.Chars, row.Due, row.Done]),
    ];

It doesn’t reference Gradio.NET and doesn’t know how many parameters the table component has. What the UI layer gets is a pile of object?, no different in kind from the strings the earlier chapters got — it just has one more layer. The boundary between business logic and UI stays where it was: TaskTable owns “which five things a row holds”, and Program.cs owns “how those five things are laid out into cells”.

Where do those five things come from? Still the “Tag Content” text from Chapter 7, one item per line. FromLines cuts each line in two, then fills in the other three columns.

    public static IReadOnlyList<TableRow> FromLines(IEnumerable<string> lines)
    {
        var rows = new List<TableRow>();

        foreach (var line in lines)
        {
            var trimmed = line.Trim();
            if (trimmed.Length == 0)
            {
                continue;
            }

            var space = trimmed.IndexOf(' ');
            var tag = space < 0 ? trimmed : trimmed[..space];
            var text = space < 0 ? "" : trimmed[(space + 1)..].Trim();

            rows.Add(new TableRow(
                tag,
                text,
                text.Length,
                FirstDue.AddDays(rows.Count * 2),
                tag is "Completed" or "Archived"));
        }

        return rows;
    }

The first two columns are cut out. Before the first space is the tag, after it the content. The last three columns are computed: the character count is the length of the content, the due date moves two days later per row in row order, and done depends on the tag. “Completed” and “Archived” count as done; everything else counts as not done.

Not one line of this code has anything to do with tables. It does the same thing as in Chapter 3: compute everything the UI is going to show first, and let the UI layer only lay it out. Switching to a table changes none of that division of labor — only that what gets “laid out” is five columns instead of one stretch of text.

headers is the column names, one per column. The sample’s five columns, in order, are Tag, Content, Character count, Due, Done, matching the five fields of TableRow one to one. That correspondence is hand-written; the compiler doesn’t check it. One headers short and the last column has no name; one too many and the extra header has no data under it. Get both wrong and the UI reports no error — it just “looks a bit off”. Misaligned headers and data are the hardest kind of problem to track down, because they look like the content is wrong.

One shortcut is to put the column names in a constant on the business side and have the UI reference that constant only.

    public static readonly string[] Headers = ["Tag", "Content", "Character count", "Due", "Done"];

Headers is defined once in TaskTable, referenced twice in BuildTableView (once for the editable table, once for the read-only one), and once each in AppendRow and ClearTable. Change a column name in one place and all four tables follow.

label is the component’s name, shown in the top-left corner of the table (the light gray “Editable table” in Figure 9-1). It’s the component’s own label; the headers are the column names given by headers. showLabel: false hides it. Both tables set label, because on the page they look nearly identical and without a label you can’t tell which is which.

9.2 datatype and Column Semantics

datatype is a string array, one entry per column, telling the component “what this column is”.

It governs two things: which editor a cell uses, and what type the server receives.

datatypeThe server receivesOn the UI
"str"stringa cell of text
"number"doublea cell with a number
"date"stringa cell with a date and time
"bool"boola checkbox

The date column comes back as a string. In the sample, that column reaches the server as text like 2026-03-02T00:00:00. To compute a number of days from it you have to call DateTime.Parse yourself; to sort by date you have to convert first, then compare. This is another example of the Chapter 3 rule “the component decides what type it accepts”. It’s called date, yet the server receives a string.

The same date column even displays differently in the two tables. In Figure 9-1 the Due column of the top table reads 2026-03-01T16:00:00.000Z, while the read-only table below reads 2026-03-02T00:00:00. One value, two spellings. The editable table parses the date into an instant and displays it in UTC; the read-only table outputs the server’s string verbatim. The eight-hour difference comes from the time zone.

That difference affects how you read the data on the UI. When you make a judgment like “the due date is March 2”, don’t look at the string on the UI — look at the value the server received. It’s the same day as the DateTime the business side put in.

The date shows in ISO format because the component does no localization. It lays the value out verbatim and doesn’t guess whether you want “March 2, 2026” or “03/02/2026”. To display it in a local format you have to format it into a string yourself — but then that column becomes str, and the checkbox and date-parsing benefits disappear with it. It’s a trade-off: if you want “a date a machine recognizes”, accept ISO; if you want “a date that’s comfortable for a person to read”, treat it as text.

What if you leave datatype out? It’s treated as str. Remove that array from the sample and the Boolean column stops being a checkbox and becomes the two words true and false; the date column stops being parsed and shows the server’s string verbatim. The UI instantly degrades from “a table” into “a pile of words arranged in a grid”.

If the array is shorter than the column count, the remaining columns are treated as str. That rule is lenient — lenient enough to be easy to forget. Write only two datatype entries for five columns and the last three quietly degrade to text, with no error visible on the UI.

A type mismatch doesn’t error either. Write “seven” into a number column and the table accepts it; what the server receives is a string of text, not a number. Write “March 2, 2026” into a date column and it displays verbatim; write 2026/3/4 and it recognizes and parses it into an instant. datatype is a hint, not validation. Real validation has to be written in the handler function yourself.

That “no error” rule has one concrete consequence. The sample’s statistics need to count “how many rows are done” from the table, and the code is written like this.

    public static TableReport Summarize(IEnumerable<IReadOnlyList<object?>> rows)
    {
        var all = rows.ToList();
        var done = all.Count(row => row.Count > 4 && IsTrue(row[4]));
        var latest = all.Count == 0 ? "(empty table)" : Convert.ToString(all[^1][1]) ?? "";

        return new TableReport(all.Count, all.Count == 0 ? Headers.Length : all[0].Count, done, latest);
    }

IsTrue handles three cases: a genuine bool, the string "true", and anything else, which counts as not done.

    public static bool IsTrue(object? cell) => cell switch
    {
        bool flag => flag,
        string text => bool.TryParse(text, out var parsed) && parsed,
        _ => false,
    };

Why accept string too? Because in a checkbox column the user doesn’t necessarily only click the checkbox. datatype says bool, but the value the server receives isn’t always well-behaved. One extra branch keeps the statistics from crashing on a single unexpected input.

The Boolean column only recognizes true. Write "true" and it counts as checked; write “no” and it counts as unchecked; write anything else and it also counts as unchecked.

There’s one easy misunderstanding with the number column. The “Character count” column is number, but it and the “Content” column are two spellings of the same thing: change one character of content and the character count should change with it. The table won’t link those for you. After you edit the content, the character-count cell still holds the old value. To make it follow, you’d have to recompute it in the change handler function and write it back; the sample doesn’t do that, because rewriting the whole table would wipe out the cell the user is editing. For tables where “one column depends on another”, the usual answer is to make the dependent column read-only, or not store it at all and compute it on the fly.

9.3 interactive and Editing Behavior

interactive decides whether the table can be edited. The sample states it explicitly for both tables: true for the top one, false for the bottom one. It doesn’t rely on the default, because changing this one parameter changes the behavior of the whole table — writing it out is more reliable than remembering the default.

An editable table has two levels of operation.

One click selects. The cell is framed in orange, a triangle appears to the left of the row-number column, and a vertical three-dot menu appears in the cell’s top-right corner.

Figure 9-2 One click selects the cell; on the right, the row, column, and column cell count are recorded

Selecting isn’t just drawing a frame. It also fires a select event, and those three lines in the “Selected” panel on the right are written by the handler function: row 0, column 1, 8 cells in the column, and the cell contains “Add two screenshots”. Where those three numbers come from is covered in 9.6.

A second click enters edit mode. The cell turns into an input box with the cursor inside. Press Enter, press Tab, or click another cell and the change lands.

The two triangles that appear on selection are the entry points for “whole row” and “whole column” — click one to select an entire row or column; the three-dot menu in the cell’s top-right corner is the cell’s menu. The sample uses none of them, and their being there doesn’t affect anything. The table ships with more than the sample uses; you can ignore what you don’t need.

A read-only table has only the first level. Clicking a cell still highlights it and still fires select, but a second click does nothing and no input box appears.

Figure 9-3 The read-only table can be selected too; the highlight and the panels all respond, you just can’t edit

This is easy to get backwards. interactive: false blocks “editing”, not “touching”. If you want to know which row the user clicked, the select event still brings back the row and column; you don’t need editing for that. The sample binds the same handler function to both tables, and the only difference on the panels is “3 cells in the column” versus “8 cells in the column”, because the bottom table has only three rows.

A read-only table is for reading, not editing. Its typical place is a result preview: a computed table sits there that the user can see, select, and copy, but not change. In the sample it’s the “comparison”. Two treatments of the same data — edit the top one and the bottom one stays put.

Figure 9-4 Edit one cell: the Edited panel holds the old value, the Change panel the new one

After the edit, what the server receives is the whole table, not that one cell. In Figure 9-4 both panels talk about “First row content”. The handler function’s parameter is an entire table, and you pull whichever cell you want out of it yourself. That design matches Chapter 3: a component passes its complete value to the handler function, and a table is no exception.

Sending the whole table back with the request has the advantage that the handler function doesn’t need to know which cell the user changed. To recompute statistics, pass the whole table to the business side and recalculate; to validate, scan from the top. The downside is that a large table gets heavy. Twenty rows is fine; two thousand rows sent on every keystroke costs the network and the server both.

The selection level has its uses too. When a user clicks a row you can show that row’s details elsewhere. The whole row is in row_value, so there’s no need to look it up again. The sample only writes the row and column numbers onto a panel; in a real feature that panel usually becomes a detail view, a small card, or a “delete this row” button. The row number the button needs is exactly the one select brings back.

Code can change the table too. The “Append row” button returns a new table with one more row; the UI swaps in the whole new block and the row numbers run from 1 to 9. That’s the same rule as “a return value replaces a component’s content” from Chapter 3 — except here what’s replaced is an entire table.

(object, object) AppendRow(DataframeTable table)
{
    var rows = table.Rows.ToList();
    rows.Add(TaskTable.Cells(new TableRow("To do", $"New item {rows.Count + 1}", 6, TaskTable.FirstDue.AddDays(rows.Count * 2), false)));

    return (new DataframeTable(TaskTable.Headers, rows), gr.Skip());
}

Two outputs, the second one gr.Skip(). This block has two tables, the editable and the read-only, each taking one output slot; “Append row” should change only the editable table and leave the read-only one as it is, so the second slot gets Skip. Chapter 3 covered what Skip is for; this is its most typical use — one event writing several outputs and changing only some of them.

DataframeTable is the table’s value type, with just two members, Headers and Rows. Building a new table means “copy the headers, swap in new rows”. It’s the same type in events: the handler function’s parameter is it, not a two-dimensional array and not JSON.

9.4 Column Width, Wrapping, and Row Numbers

The easiest way for a table to look bad is width.

columnWidths is one pixel width per column. The sample gives five numbers: Tag 80, Content 240, Character count 70, Due 220, Done 90. The widths are there so the “Content” column gets the lion’s share — it holds a whole sentence, while the other columns hold a few characters, a number, a checkmark.

Leave widths out and the component divides them by content itself. With many columns and long content, the result is often not what you want: short columns get stretched wide, long columns squeezed into a strip. Fixed widths at least guarantee it looks the same every time, and let you decide the ratio between “Content” and “Character count”.

The price of fixed widths is “it might not fit on another machine”. Pixels don’t follow the window; make the browser a bit narrower and the last columns get cut. Responsive widths don’t have that problem, but they redistribute when the column count changes, so the same table looks different on two machines. Fixed widths are chosen for a book’s sample because the screenshots need to be stable; for a real application, the choice depends on whether users mostly use it on a large screen or a small one.

Fixed widths bring a new problem: not fitting. Add up the column widths past the container and the right-hand columns get cut, showing only half. A checkbox gets sliced into a strip, a date keeps only its first few characters. The table itself scrolls horizontally — put the mouse over the body and scroll left and right, or move the active cell with the arrow keys, and the cut columns come back into view.

There’s a crude way to judge “will it fit”: add up columnWidths and compare it with the table container’s width. In the sample the five widths add up to 700, and with the forty-odd pixels of the row-number column they just fit inside the container; one more column and you’d be scrolling horizontally.

When it doesn’t fit, there are three ways to handle text that’s too long for a cell.

Truncate. maxChars cuts by character count and adds an ellipsis after the cut. The sample’s comparison table sets it to 12, and the same passage is reduced to “Wrap by chara…”.

Wrap. wrap: true folds long text into several lines; the cell grows taller and not a single character is lost.

Widen. Increase that column’s width so it fits. Column widths are pixels, not percentages, so widening means adding up the total yourself and keeping the table narrower than its container.

Figure 9-5 Three comparison tables: truncate, wrap, not enough headers

The same passage, truncated on the left and wrapped in the middle: you can see the trade-off at a glance. Truncating saves height but hides part of the text; wrapping shows everything but the row heights don’t line up. A table can have both, but within one column it’s best to be consistent — half truncated and half not makes readers think the content lengths differ.

maxChars affects display only, not the stored value. Set it to 12 and the handler function still receives the whole sentence; the only thing cut is the characters on the UI. That’s the exact opposite of a text box’s maxLength: maxLength stops the user typing more, while maxChars stops the user seeing it all. To limit input length you have to check it in the handler function.

showRowNumbers: true adds a row-number column on the far left. Row numbers are signposts for people: “the one in row 5” is easier to say than “the archived one”. They stick with the original table — after search filters, the numbers are still the original ones (you’ll see this in 9.5).

The row-number column counts in neither headers nor columnWidths. Give five columns widths and you get six columns on the UI, the extra one being row numbers. That column takes part in horizontal scrolling too, but it’s the leftmost column, so it doesn’t have far to go.

showRowNumbers is independent of interactive; a read-only table can have row numbers too. The sample’s read-only table leaves it off because three rows are easy enough to count.

Row height follows the content. Eight rows, one line of text each, fits on one screen; switch to wrap: true and long content stretches to two lines, so the same table is suddenly taller. With dozens of rows one screen isn’t enough and the table pushes the page long. The table is the tallest block on this page, so it usually sits lower down rather than at the very top.

9.5 The Search Box and Filtering Rows

showSearch has three settings: "none", "search", "filter". The default is "none", with no box shown to the right of the header.

The other two both put an input box to the right of the header; the difference is the placeholder inside it — Search... for "search", Filter... for "filter". What happens after you type is the same: only matching rows remain and non-matching ones are hidden. You can’t tell the two modes apart on the UI, so which you pick mostly comes down to which placeholder you prefer.

Figure 9-6 Search for “chapter 5”: only one row remains, still with row number 3

Notice the row number in Figure 9-6. The one remaining row still reads 3, not 1. Searching is “hiding the non-matching rows”, not “re-laying-out a new table”. That’s useful when you talk to users: “row 3” always means the same row, searched or not.

Search is a pure UI action that never reaches the server. In Figure 9-6 the three panels don’t move at all, still showing “No cell has been clicked yet”. Typing a search term fires no event; the handler function has no idea anyone is searching. So search can’t replace a query. To really fetch data by a condition, you have to let the handler function take the condition and filter, as in Chapter 7.

That’s also the search box’s boundary: it can only filter “the rows already on the page”. With eight rows in the table, no matter how precise the search, it’s picking from those eight; to search the twentieth row you first have to send twenty rows up.

Search for a word that doesn’t exist and the header stays, the body is empty, and there’s no “no results” message. If you want users to know a search came up empty, you have to arrange that on the page yourself.

A read-only table can search too. The sample’s read-only comparison table leaves search off, but on or off has nothing to do with interactive; the two parameters mind their own business. A read-only table with search on lets the user filter, view, and select — just not edit.

The search box’s position is fixed to the right of the header; it can’t be moved. For a “search somewhere else”, use an ordinary Textbox plus a button and let the handler function filter. That’s the Chapter 7 approach, and it’s a different thing from the search box here.

There’s also a difference in division of labor. The search box filters “this one table that was already sent up”, with the handler function none the wiser; Chapter 7’s filtering has the handler function recompute by condition, and the result can land on any component. The former is fast — no server round trip, one filter per keystroke; the latter can reach “things that aren’t in the table”, like looking up another data set by tag. Small table with the condition being just “do these characters appear in the text” — use the search box; large table, or more than one filter condition — use a handler function.

9.6 Callbacks for Edit, Select, and Change

The three events fire at different times and bring back different values.

Figure 9-7 Select, Edit, Change: when they fire and what they bring back

select fires when you click a cell and brings back “that cell” and its context.

string OnSelect(DataframeTable table, SelectData pick)
{
    var position = pick.Raw is JsonObject payload && payload["index"] is JsonArray pair
        ? pair.Select(node => node?.GetValue<int>() ?? -1).ToArray()
        : [];

    var row = position.Length > 0 ? position[0] : pick.Index ?? -1;
    var column = position.Length > 1 ? position[1] : -1;
    var columnCells = pick.Raw is JsonObject raw && raw["col_value"] is JsonArray cells ? cells.Count : 0;

    return $"""
        **Select** row {row}, column {column} · {columnCells} cells in the column

        Cell: {pick.Value}
        """;
}

SelectData has four members: Value, Index, Selected, Raw. Value is the value in the cell, Index is the row number, and Selected is the selection state for this once (click a cell and it’s true). The row and column numbers aren’t in Index; you get them from Raw. Raw["index"] is a two-element array, the first being the row, the second the column.

That division is easy to mix up. Index is only a row number; to get “which row and which column” you must go through Raw. The sample’s approach is to pull that array out of Raw first and fall back to Index if it’s not there, keeping both paths open.

Raw also holds two ready-made things: row_value is the whole row, col_value the whole column. The sample uses the length of col_value to report “8 cells in the column”. A count is enough to tell the user how many entries the column has; no need to iterate it yourself.

SelectData, like Progress, is injected by type and doesn’t take up a slot in inputs. The binding above lists only one input, [sheet.Grid], yet the handler function has two parameters, the second filled in by the framework by type. The rule at the end of Chapter 5 gets used once more here.

The other two events are covered together.

string OnEdit(DataframeTable table)
{
    var report = TaskTable.Summarize(table.Rows);

    return $"""
        **Edit** before the change: {report.Rows} rows × {report.Columns} columns

        First row content: {Cell(table, 0, 1)}
        """;
}

OnEdit and OnChange look almost identical; the only difference is that one phrase, “before the change” and “after the change”. The two events really do carry different tables.

  • edit brings back the table before the change. The user types “Write the chapter 5 outline” into a cell, and the first row edit receives is still “Write the chapter 4 outline”.
  • change brings back the table after the change. For the same action, the first row change receives is already the new value.

Need the old value to compare, undo, or log an audit — use edit; need to save the new value or recompute statistics — use change. Bind both and you get “what it changed from and to”, with both ends of one edit in hand.

Three details that are easy to trip over.

It fires even when the value doesn’t change. Double-click into a cell, change nothing, press Tab out — both events still fire, and the tables they bring back are identical. So don’t treat “it fired once” as “the user changed something”. Compare the tables before and after, or compare a particular cell’s value.

The order isn’t fixed. For one submit, edit and change are two independent jobs, and which arrives first isn’t guaranteed. In the sample the two panels each write their own, so the order isn’t visible; if both events wrote to the same output, which one ends up displayed would be undefined.

Each fires twice. For one submit, edit fires twice and change fires twice, with identical content. That has nothing to do with whether an output is declared; the front end sends the same submit twice. Handler functions therefore have to be written to run repeatedly. Appending one log line becomes two; applying one deduction deducts twice. The sample’s handler functions only “compute this piece of text”, so running them twice gives the same result and you can’t tell.

Changing the table from code fires only change. Click “Append row”: the table becomes nine rows, the “Change” panel updates, the “Edited” panel doesn’t move. edit only recognizes a cell a human edited.

triggerMode, Then, Success, Failure — all covered in Chapter 5 — work on tables just the same. All three events are ordinary events and their return value is an ordinary Dependency. The sample sets no parameters on them and uses the defaults.

Which of the three events to pick can be worked backwards from “what you want”.

  • Only need to know which cell the user clicked — use select. It’s the lightest: one click fires it, and it doesn’t bring the whole table.
  • Need both ends of “before and after” — bind both. To display “changed from 7 to 9”, that’s the only way to get it.
  • Only need the new value — bind change. Code-driven table changes fire it too, so one path covers both sources.
  • Only need the moment a human edits — bind edit. Code-driven table changes don’t fire it; that’s the one thing that separates it from change.

Of the four, the one most often bound unnecessarily is edit. Its semantics are narrow: it fires only “when the user finishes an edit”, and it fires even if the value didn’t change. Before binding it, ask one question: do you want the old value, or the signal “the user did something”? Use it for the former; for the latter you have to compare yourself.

9.7 Empty Tables and Row/Column Limits

What happens when you clear the table? The header stays, and the body is left with a single dashed-outline row with a “+” in the middle.

Figure 9-8 After clearing: the header is still there, the body is a single “+” row

object ClearTable(DataframeTable table)
    => new DataframeTable(TaskTable.Headers, []);

Clearing means replacing Rows with an empty array and carrying the headers back unchanged. An empty table and “no table at all” are two different things. With the header still there, the user knows what belongs here; if the whole block vanished, the user would only think the feature was gone.

That “+” row is there to be clicked: one click adds an empty row and you fill it in directly. It’s the table’s own built-in entry for creating a row; you don’t have to write a handler function for it. But it isn’t “pure UI” — once a row is added the table’s value has changed, and change fires once (the “Change” panel goes from “after the change: 0 rows” to “after the change: 1 row”). The sample’s other “Append row” button takes a different route: it returns a new table and brings default values along. The two ways of adding a row coexist without conflicting.

After clearing, the “Change” panel reads “after the change: 0 rows”, and Cell can’t get a value, so it shows “(no such cell)”. In the handler function you have to check the row count before reading a cell; you can’t skip that check.

static string Cell(DataframeTable table, int row, int column)
    => table.Rows.Count > row && table.Rows[row].Count > column
        ? Convert.ToString(table.Rows[row][column]) ?? "(empty)"
        : "(no such cell)";

You need both checks: first whether the row exists, then whether that row has the column. After a user clears and then clicks “Append row”, the first row is there — but if some return ever comes back with rows of uneven length, the second check earns its keep.

Can the number of rows and columns be capped? Look at two declarations first.

rowCount and columnCount are each a two-tuple of a count and a mode ("fixed" or "dynamic"). They sound like “this table has exactly this many rows and columns”, but they don’t. What they declare is a starting point, not an upper bound.

  • More data than declared — no truncation. The right-hand comparison table is the proof: headers gives only two columns, the data gives four, all four columns appear on the UI, and the two extra headers are the sequence numbers 3 and 4. Aligning headers with data when you write the code is easier than guessing those numbers afterward.
  • Less data than declared — no empty rows added. Declare 6 rows with 2 rows of data and the UI shows 2 rows; it won’t add four empty ones waiting to be filled.
  • An empty table isn’t padded to the declaration either. Declare 5 rows with a null value and the UI still shows the header plus one “+” row.

So the sample simply leaves these two parameters out; writing them doesn’t affect display, so it might as well not. To really cap things, count in the handler function: when table.Rows.Count exceeds some limit, throw an exception or return a line of notice the user can see. How to write exceptions and notices is covered by Failure in Chapter 5 and by Chapter 17.

That’s another difference between a table and a text box. A text box has maxLength: hit the limit and you can’t type more. A table has no equivalent — row count, column count, and characters per cell (maxChars only governs display, not storage) all have to be blocked yourself.

Extra columns using sequence numbers as headers has another use: debugging. When there’s more data than headers, it’s usually that the column count Cells flattened doesn’t match Headers. A column suddenly appearing that starts with “5” is faster than counting through the code.

An empty table has another use: build a table from scratch for someone to fill in. Give it an empty array and a set of headers, and the page shows the header plus one “+” row; a few clicks and the user has filled out a table. The sample’s “Clear” takes exactly this route — after clearing, the table is still there and the user can keep adding to it. That’s cleaner than “dropping in a few fake rows as placeholders”: fake data gets taken for real, an empty table doesn’t.

The same code used once for “clear” and once for “create” — the only difference is context. A table’s value is, after all, “headers + rows”; rows being empty makes it a new table.

9.8 Chapter Summary

Dataframe holds an entire table in one component. Its value is a two-dimensional structure, rows on the outside and cells on the inside; headers gives one name per column, datatype one type per column, and both arrays must line up with the data’s columns. Put the column names in a constant on the business side and have the UI reference it; change the constant in one place and both sides stay in sync.

datatype decides the editor and the type the server receives: str is a string, number a double, date a string (ISO format, not DateTime), bool a Boolean. Leave it out and columns are treated as str; make the array short and the remaining columns are str too. A type mismatch doesn’t error — datatype is a hint, not validation, so you write the validation yourself.

The same date value displays in UTC in the editable table and verbatim in the read-only one. Judge dates by the value the server receives, not by the UI.

interactive blocks editing, not touching: a read-only table can still be selected and still fires select. An editable table selects on one click and edits on two; press Enter or Tab to land the change, and the server receives the whole table. Code-driven changes use the return value, and when one event writes several outputs but changes only some, write Skip for the rest.

columnWidths sets widths in pixels; when it doesn’t fit, scroll horizontally. For text that’s too long, truncate with maxChars (adding an ellipsis) or wrap with wrap: true — pick one and stay consistent within a column; maxChars affects display only, not the stored value. showRowNumbers adds a row-number column, which counts in neither headers nor columnWidths.

showSearch has three settings. "none" shows no box; "search" and "filter" both “leave only matching rows after you type”, differing only in the placeholder. Search is a pure UI action that fires no event and doesn’t renumber rows; when nothing matches the body is empty but the header stays; it can only filter rows already on the page.

The three events each cover one part: select brings back the cell’s value, the row number, the whole row, and the whole column; edit brings back the whole table before the change; change gives the whole table after it. Bind both and you have “what changed from and to”. They fire even when the value doesn’t change, the order isn’t fixed, and each fires twice. Handler functions must be safe to run repeatedly — don’t treat “it fired once” as “the user changed something”. Code-driven table changes fire only change.

An empty table is a header plus one “+” row, not a blank space. rowCount and columnCount declare a starting point, not an upper bound: more data isn’t truncated, less data adds no empty rows, and an empty table isn’t padded. To cap it, count in the handler function yourself, and check the row first, then the column.

The data in the table still can’t be saved. Refresh and the eight rows go back to their initial values; edits live only on the page. Saving has to wait for state in Chapter 14.

The next chapter switches to a different kind of content: one chart drawn out, a pile of images arranged into a wall.

Chapter 10. Charts and Galleries

The table in the previous chapter spread the tasks into cells: Tag, Content, Character count, Due, Done. Cells are good for reading one at a time, not for seeing at a glance “which tag has the most characters” or “whether the character count rises over time”. Questions like that need to be drawn as charts.

This chapter adds two blocks to the workbench. One draws the task table as six charts; the other arranges six cards into a wall. The first is about “how data becomes a chart”, the second about “how images are laid out into a surface”. The two don’t look related, but they tell the same story about division of labor: the business side shapes the data into the form the component wants, and the component does the drawing.

Either you assemble the chart JSON yourself and write it into the component, and the component only passes it to the front end unchanged; or you hand over a few columns of data and let the component compute coordinates and group them itself. The first is flexible, the second is convenient.

The gallery side covers a different set of parameters: how many images per row, how many rows, how an image fits into its cell, and which one is shown first on load. Plus three events: what you do and don’t get when you click an image, open the preview, and close the preview.

10.1 Plot and Chart Data Passthrough

Plot takes a PlotData. Two fields: a library name and that library’s own drawing.

plotly = gr.Plot(
    value: new PlotData("plotly", TaskChart.PlotlyBars(rows)),
    label: "Hand-built Plotly");

The first field is the library name, one of four: plotly, bokeh, altair, matplotlib. The front end uses that name to find the matching plotting library and passes the second field to it unchanged. The second field is the JSON that library recognizes: plotly wants a plotly figure, altair wants a vega-lite spec, matplotlib accepts a base64-encoded image. The component doesn’t interpret a single byte.

That’s all “passthrough” means. It doesn’t care what’s drawn inside, only about delivering the string. The upside is a high ceiling: anything plotly can draw, you can draw here, including 3D, maps, and animations that the component itself can’t make. The downside is a low floor too: axes, colors, aggregation, sorting — all of it has to be computed on the business side and written into that JSON.

The Plotly bar chart in the sample draws “how many tasks each tag has”. Counting that number uses a business-side method.

    public static IReadOnlyList<(string Tag, int Count)> CountByTag(IEnumerable<TableRow> rows) =>
    [
        .. rows.GroupBy(row => row.Tag).Select(group => (group.Key, group.Count())),
    ];

After counting, it still has to be assembled into JSON. The sample doesn’t hand-write the string; it serializes an anonymous object instead.

    public static string PlotlyBars(IEnumerable<TableRow> rows)
    {
        var counts = CountByTag(rows);

        var figure = new
        {
            data = new[]
            {
                new
                {
                    type = "bar",
                    x = counts.Select(pair => pair.Tag).ToArray(),
                    y = counts.Select(pair => pair.Count).ToArray(),
                    marker = new { color = "#1d4ed8" },
                },
            },
            layout = new
            {
                title = new { text = "Tag counts (Plotly)" },
                height = 300,
                margin = new { t = 40, r = 20, b = 50, l = 50 },
            },
        };

        return JsonSerializer.Serialize(figure);
    }

The anonymous object’s field names become the JSON keys, so they’re all lowercase here: data, layout, type, marker. Change one to uppercase Data and plotly won’t recognize it — nothing appears, and no error is reported. That’s the easiest trap when assembling JSON: C# compiles fine and the UI is a blank space.

A wrong library name behaves the same. new PlotData("chartjs", json) goes through, the server doesn’t stop it, and the front end gets a library name it doesn’t know, so the chart area stays empty. The four names are a hard constraint; there is no fifth.

The left-hand path in Figure 10-1 is exactly that: the business side counts, assembles JSON, wraps it in PlotData, the component passes it to the front end unchanged, and the front end picks the library by name. The right-hand path is next section’s NativePlot. Both routes reach the same place in the front end; the only difference is “who computes”.

Figure 10-1 Plot passthrough and NativePlot direct drawing: one gives JSON, the other a table

Plot has no title, xTitle, or the like. Its parameter list is short: value, format, label, every, container, scale, minWidth, visible, plus the few that every component has. What text appears on the chart and what the axes are called all live in the JSON’s layout — the sample’s title.text and margin do exactly that. On the passthrough route, the chart’s appearance belongs to the JSON; the component only passes the JSON to the front end unchanged.

format is for images and defaults to "webp". The matplotlib route hands the component an image, and the component handles it in that format. The sample goes through plotly, where the format is irrelevant, so it’s left alone.

Give it an empty value and the chart area sits empty. The sample’s “Clear” button returns six empty values, and all six charts vanish together — the blocks remain, blank inside. It’s the same idea as a cleared table keeping only its header: the space stays, so the user knows something belongs here.

So when should you take this route? Three cases to consider. One, the chart you need is one the component can’t draw — 3D, maps, Sankey diagrams and the like. Two, you already have a piece of plotly JSON on hand, exported from somewhere or generated by a script. Three, the styling is fine-grained down to the width of each line and the font of each tick, beyond what the component’s few parameters can cover.

For everyday charts beyond those, the three components in the next section are less work.

10.2 LinePlot, BarPlot, and ScatterPlot

NativePlot is the other route. Instead of JSON you give it a table, tell the component “which column is the x-axis, which is the y-axis, which decides the color”, and it computes the rest itself.

Three factory methods correspond to three chart types: LinePlot for lines, BarPlot for bars, ScatterPlot for points.

            var line = gr.LinePlot(
                value: series,
                x: "Due",
                y: "Character count",
                color: "Tag",
                title: "Due and character count per task",
                xTitle: "Due",
                yTitle: "Character count",
                xAxisFormat: "%m-%d",
                xLabelAngle: 45,
                yLim: new double?[] { 0, 40 },
                height: 260,
                label: "Line chart");

The three factories’ parameter lists are nearly identical; go through them one by one and they line up. All have value, x, y, color, title, xTitle, yTitle, colorTitle, xBin, yAggregate, xLim, yLim, xAxisFormat, yAxisFormat, xLabelAngle, height, tooltip, caption.

There’s only one difference: what gets drawn. At runtime all three types are the same component, with a mark field in the value — line for the line chart, bar for the bar chart, point for the scatter plot. Apart from that field, the data the three send to the front end is identical.

That explains why their parameter lists can look the same: the three charts are the same thing, with only the final stroke drawn differently. It also explains why changing one parameter often works for all three. color means grouping in a line chart, side-by-side bars in a bar chart, and point color in a scatter plot — the meaning is consistent.

value can be one of two things. One is a “column name → values” dictionary, which is what the sample uses.

    public static IReadOnlyDictionary<string, object?[]> Series(IEnumerable<TableRow> rows)
    {
        var points = Points(rows);

        return new Dictionary<string, object?[]>
        {
            ["Tag"] = [.. points.Select(point => (object?)point.Tag)],
            ["Character count"] = [.. points.Select(point => (object?)point.Chars)],
            ["Due"] = [.. points.Select(point => (object?)point.Due)],
            ["Order"] = [.. points.Select(point => (object?)point.Order)],
        };
    }

Four columns, eight values; one task takes one slot in each column. The dictionary keys are the column names, and the “Due” in x: "Due" is exactly one of those keys. A misspelled key doesn’t error — you just get an empty chart. Like a wrong headers, the mistake is in the name and the UI only looks “a bit off”.

The other is NativePlotData, with four fields: Columns, Data, Datatypes, Mark. It’s the dictionary flattened out; the component converts the dictionary into it and sends it to the front end. To specify a column’s type yourself (say, treating a column of numbers as categories), you have to construct it directly — the dictionary route leaves no opening for that.

The component infers a column’s type from its values, by three rules.

  • Numeric values are quantitative, drawn to a numeric scale;
  • Date values are temporal, drawn on a time axis;
  • Everything else is nominal, drawn as categories.

Booleans count as numeric, because they work as 0 and 1. An empty column counts as categorical, because such a column has no members at all.

The sample’s four columns come out as: Tag categorical, Character count quantitative, Due temporal, Order quantitative. That’s why the line chart’s x-axis becomes a time axis and the bar chart’s x-axis is laid out as equal-width slots. The component inferred these types from the values.

One detail to know up front about the date type: what it sends to the front end is a millisecond count, not a string. The tooltip in Figure 10-4 reads 2026-03-02 08:00:00. The business-side DateTime is midnight on March 2, and the extra eight hours on the chart come from the time zone. The date column in Chapter 9 behaves the same way. Server and front end understand “an instant” one time zone apart, so keep that in mind when reading the values.

Which of the three to pick depends on the question you’re answering.

QuestionUseWhy
How it changes over timeLinePlotLines join the points, so the trend is visible at a glance
Who has more, who has lessBarPlotBar lengths are easier to compare than angles
How two numbers relateScatterPlotPoints spread over a plane, so correlation or its absence shows

The sample feeds the same data to six charts so you can see “one data set, six questions”. All six share a single series; none of them computes it a second time.

With six charts side by side, one more thing depends on label. In Figure 10-2 each chart has a line of small text in its top-left corner (“Line chart”, “Total”, “Count”, “Binned”, “Scatter”) — that’s the component’s label, not the chart’s title. The title sits at the top of the chart and says what the chart draws; the label sits at the block’s corner and says which component this block is. Both are set so the six charts can be told apart when placed together. showLabel: false hides the label; the title can’t be hidden — it lives in the JSON or the title parameter.

When the data is empty, the six charts are six blank blocks, with no error and no message. To see what “no data” looks like, click “Clear”.

Figure 10-2 The chart area: the same task table, one line chart plus three bar charts

The line chart in Figure 10-2 has only three line segments, yet the legend lists five tags. Nothing was lost: after grouping by color, each group gets its own line, and a group with a single point can’t form a line. The sample’s eight tasks spread over five tags, two of which have only one task each, so those two are left with just a name in the legend. To make a single point visible you need a scatter plot — a scatter plot draws points, and one point still gets drawn.

10.3 Coordinates, Grouping, and Aggregation

x and y are both column names. Give two columns and the points are laid out on those two. The sample’s line chart uses “Due” for the x-axis and “Character count” for the y-axis, so each task becomes a point in the plane whose x-coordinate is its due date and y-coordinate its character count.

Give a wrong column name, or one that doesn’t exist, and the chart is empty — no exception, no message.

color is also a column name, but it governs “splitting by this column”. Split a line chart by tag and each tag gets a line and a color; split a scatter plot by tag and the point color follows the tag. Omit color and all points count as one family — one connected line, one color for every point.

Grouping has two consequences. First, the legend lists the values of that column — five tag names in the sample. Second, each group’s points form their own line. That’s why “a single point can’t draw a line” from 10.2 shows up.

yAggregate decides “how multiple values at the same x-coordinate collapse into one”. Three settings: "sum" adds them, "count" counts entries, "mean" takes the average. The sample draws three bar charts; the first two share the tag as their x-axis and differ only in aggregation.

                sum = gr.BarPlot(
                    value: series, x: "Tag", y: "Character count", yAggregate: "sum",
                    title: "Total character count per tag", height: 300, label: "Total");

                count = gr.BarPlot(
                    value: series, x: "Tag", y: "Character count", yAggregate: "count",
                    title: "Number of entries per tag", height: 300, label: "Count");

                bin = gr.BarPlot(
                    value: series, x: "Character count", xBin: 2, y: "Character count", yAggregate: "count",
                    title: "Character count in two-character bins", height: 300, label: "Binned");

The two charts have identical data and both label their y-axis “Character count”, yet what they draw is completely different. Compute the same data once for each of the three settings and the results look like this.

AggregateTo-doIn ProgressDoneTo ConfirmArchived
sum121610108
count22211
mean685108

sum adds the character counts of the same tag, count counts “how many entries this tag has”, and mean is “the average characters per entry”. One column of data, three questions, three answers. The mean row in the table isn’t drawn as a chart — it’s not among the three charts; the algorithm is the same, so you can compute the values yourself against it.

count has one oddity: it doesn’t use the y-column’s values, yet that column still has to be written. Write x: "Tag" with yAggregate: "count" and no y — the server accepts it, but the front end errors while drawing and the chart area is left blank. All three bar charts in the sample dutifully write y: "Character count", even though count never looks at it.

Now look at the y-axis ticks. The Total chart runs from 8 to 16, the Count chart from 1.0 to 2.0. The counts are plainly integers, yet the ticks carry decimals. Because that column was inferred as quantitative, the axis is drawn as a numeric axis and decides its own tick spacing — it doesn’t switch to integer ticks just because “the values happen to be integers”. To make it tidy you’d have to turn the column into a categorical one, but then bar heights would no longer be compared by value.

The scatter plot uses the “Order” column on its y-axis, and not for looks. Among the eight tasks, character count has only seven distinct values from 4 to 10; when two numbers match, two points overlap and it looks like one is missing. Put “which entry” on the y-axis and each task gets its own row, so all eight points spread out. A scatter plot shows the relation between two numeric columns; pick a y-column where “every row differs” and the points won’t coincide — and Order is exactly such a column.

xBin cuts the x-axis column into bins and then aggregates. The sample’s third chart uses xBin: 2, so the axis is split two characters per bin: four to six, six to eight, eight to ten. Each bin gets one bar whose height is how many entries fall in it.

                bin = gr.BarPlot(
                    value: series, x: "Character count", xBin: 2, y: "Character count", yAggregate: "count",
                    title: "Character count in two-character bins", height: 300, label: "Binned");

Binning is a bar-chart-only technique; line and scatter plots don’t use it, since their x-axis is continuous to begin with. xBin gives the bin width, not the bin count. Write 2 and it’s two characters per bin: eight character counts between 4 and 10 naturally fall into three bins. Change it to 10 and all eight numbers land in the “zero to ten” bin, leaving a single bar.

color and aggregation can be used together. Then color splits by the color column, each bar gets its own color, and the legend still lists that column’s values. To assign colors yourself, use colorMap — a “value → color” dictionary: give a few values their colors and the rest use the default. The sample doesn’t set it, so all five bars are one color, which doesn’t affect comparing lengths; to really tell “Done” and “To-do” apart, colorMap is easier to distinguish than the default palette.

All three bar charts in the sample set the aggregation explicitly. Leave it out and how multiple values at one x-coordinate are placed depends on the chart’s own default — not something you can reliably guess. If you want merging, write sum, count, or mean clearly; don’t leave it to the default.

Placing the three bar charts side by side serves one more purpose: seeing what “the x-axis changed” means. The first two use the tag as the x-axis, the third uses character count. Same data, and switching the x-axis changes the story the chart tells. That’s also the first step in choosing a chart: decide which column goes on the x-axis.

Figure 10-3 Scatter plot and Plotly: on the left the component draws, on the right you assemble it yourself

The right-hand chart in Figure 10-3 is the passthrough from 10.1: the bar heights are entry counts computed by the business side per tag, the color is hard-coded in the JSON, and even the margins are filled in by hand. In the left-hand scatter plot, coordinates, legend, and axes are all computed by the component from four columns of data. Put them side by side and the difference between the two routes needs no further explanation.

10.4 Titles, Ranges, and Tooltips

title is the chart’s title, drawn centered above it. xTitle, yTitle, colorTitle are the three axis names — x-axis, y-axis, legend. The sample’s line chart sets all four, so “Due and character count per task” sits at the top and “Due”, “Character count”, “Tag” sit against their axes.

All four are plain text: whatever you write is what shows, and they take no part in computation. Omit title and the space above the chart is empty but takes no room; omit an axis name and the axis edge is empty. With many charts, titles are indispensable — six charts side by side with no titles can’t be told apart.

xLim and yLim are each a two-number array, lower bound and upper bound. The sample’s line chart pins the y-axis to 0 to 40.

                yLim: new double?[] { 0, 40 },

Pinning means points outside the range aren’t drawn. The sample’s character counts max out at 10, far from 40, so in practice this setting only stretches the y-axis and squeezes the three lines into the lower half. With a data set whose counts reach 60, the points above 40 disappear — they’re still there, just outside the window.

A range and “truncated data” are two different things. Truncation means data is missing; a range only means it isn’t drawn. Remove yLim and the blocked points come straight back, because the data was always there — only the window changed.

The range parameter is meant for continuous axes. The sample pins only the line chart’s y-axis, which is a numeric axis — the only kind where pinning makes sense. When the x-axis is dates or categories, pinning a range means “only look at this stretch”, but those slots are labels, not numbers, so what to pin depends on the data itself.

The most common use of a fixed range is “several charts sharing one ruler”. If each of six charts sets its own y-axis from its own data, one bar reaches 16 and another 2, and side by side they look eight times apart; pin them all to 0 to 20 and the lengths become comparable. The sample doesn’t do this, because the six charts have different x-axes and their bar lengths weren’t directly comparable anyway.

xAxisFormat controls how dates are written on the axis. The default writing is two lines: the time on top, the date below. All of this sample’s data falls at the same instant, so every slot on the top line reads “12 PM” — it looks broken, and you have to read the date from the line below.

Change it to "%m-%d" and only month and day remain, written on a single line.

                xAxisFormat: "%m-%d",

This parameter governs the writing, not the spacing. How many ticks there are is decided by the axis from the range. The sample’s due dates span fourteen days, and the axis picked a half-day interval, so each date appears twice — March 2, March 3, another March 3, March 4… Those repeated dates correspond to one midnight tick and one noon tick, and once the format hides the time, the two ticks look identical.

When they crowd together, tilt the labels.

                xLabelAngle: 45,

Tilted, each label takes less horizontal width, so twenty-odd dates fit. The cost is taller rows — space has to be left at the bottom of the chart.

tooltip is the hover box. Its default is "axis". Hover anywhere on the chart and it finds the nearest point and lists that point’s values for every column. Figure 10-4 shows the mouse resting on the first point.

Figure 10-4 The hover tooltip: character count, due, and tag columns are all there

The tooltip has three lines: Character count 7, Due 2026-03-02 08:00:00, Tag To-do. It lists “this point’s value in every column”, not “the few values you care about”. The eight-hour offset on the Due column shows up most clearly here.

To show only a few columns you can give tooltip a list of column names. The sample once wrote ["Tag", "Character count"], and on hover all three columns were still listed. The parameter doesn’t narrow the columns — with or without it, all three show — so the sample leaves the default "axis" and doesn’t set it again. "none" turns the tooltip off, "data" lists data without the axis; both are useful when you only want to look at the chart and not check numbers.

The tooltip on a bar chart is a different matter. Hover over the “Done” bar and it shows Character count 10. Ten is that tag’s total character count, yet the tooltip still writes the column name “Character count”, not “Total”. That’s because the tooltip lists “this cell’s values in each column”, and the aggregated number lands in the Character count column with its name unchanged. When reading it, know you’re looking at an aggregate, not one row’s character count.

height is the block’s height in pixels. It isn’t the same as the chart’s own height. The chart draws at its own size, and if the block is shorter, the bottom gets cut off. The sample’s bar charts started at 240, which clipped the bar bottoms and the x-axis labels; setting them all to 300 made the charts whole. This parameter adjusts “how much space is left”, not “how big the chart is”.

caption is the explanatory text below the chart — plain text, not part of the tooltip. It and title sit one above, one below: one says “what this chart draws”, the other “where this chart came from”. The sample doesn’t use it; the figure captions live in the book, and an extra line on the UI would only crowd it. In a product, caption suits notes like “data current as of”.

Clearing the charts follows the old path from Chapter 3: the handler function returns empty values and the components go empty.

(object, object, object, object, object, object) ClearCharts()
    => (null!, null!, null!, null!, null!, null!);

Click “Clear” and all six charts vanish together, blocks still there and empty inside. Click “Draw charts” and all six come back.

(object, object, object, object, object, object) Draw(string items)
{
    var rows = TaskTable.FromLines(items.Split('\n'));
    var series = TaskChart.Series(rows);

    return (series, series, series, series, series, new PlotData("plotly", TaskChart.PlotlyBars(rows)));
}

Six outputs for six components; the first five are the same dictionary. Those five charts read the same data, so there’s no reason to compute it five times. The sixth is the Plotly chart, which wants a PlotData, so it gets wrapped separately. The items input is the content of the “Filter” text box on the left. Edit a few lines, click “Draw charts”, and all six charts change with them. Where a chart’s data comes from and when it’s recomputed is still the Chapter 3 rule.

Gallery takes a sequence of entries. An entry can be a path, a URL, an image object, bytes, a stream, or a combination of “image and caption”. The sample uses GalleryEntry.

static GalleryEntry[] Entries(IEnumerable<GalleryCard> cards) =>
[
    .. cards.Select(card => new GalleryEntry(ImageBook.PathOf(card), card.Caption)),
];

Two fields: image and caption. The caption shows below the image and stays with it when enlarged. Each of the sample’s six cards has a caption — “Line wrapping rules”, “Event table”, “Screenshot list”. Those words aren’t in the image; the entry carries them.

A path can be relative or absolute. The sample gives absolute paths, built from the output directory’s assets.

    /// <summary>The images ship with the app; at runtime they are looked up under assets in the output directory.</summary>
    public static string Folder => Path.Combine(AppContext.BaseDirectory, "assets");

The image files ship with the project, so at runtime there’s no looking elsewhere. Point the path at a file that doesn’t exist and the UI shows a broken-image frame, with no error — the same behavior as an <img> tag.

There are three ways to write an entry, all with the same effect: give just a path and no caption shows under the image; give a two-tuple (image, caption); or give a GalleryEntry. The sample uses the third, because named fields tell you which is the image and which is the caption when you read the code.

Once an image is handed to the gallery, the file is copied into the app’s own cache directory. The sample’s six PNGs go across unchanged, byte count intact; the gallery doesn’t re-encode, it just moves the file to a directory the front end can fetch from. The gallery doesn’t re-encode — it treats “something already an image” as a file to move and sends it to the front end as-is.

type decides what the handler function receives; it defaults to "filepath", which gives a path string. The sample only puts images into the gallery and never reads them back, so it uses the default "filepath".

Layout is set by three parameters: columns, rows, height.

columns is how many images per row. The sample’s wall sets 3, so six images form three columns and two rows. rows is the maximum number of rows; leave it out and it’s computed from the entry count — six images in three columns naturally make two rows. The sample’s “six in one row” block sets rows to 1, squeezing all six into a single row.

height is the block’s height. Together with rows it decides how big each cell is: block height divided by row count is one cell’s height. Give 500 with three columns and each cell is about 250 wide by 250 tall; give 180 with one row and each cell is only 180 tall, so the images are flattened.

When the three parameters don’t work together, the most common result is cropping. The block height is fixed, so the cells are fixed too, but the image isn’t necessarily that aspect ratio. That’s when you look at objectFit.

  • "cover" scales the image up to fill the cell and crops the excess;
  • "contain" shrinks the image to fit inside the cell and leaves the leftover space blank.

The sample’s wall uses cover: the image fills the cell and its edges are cropped. The color band on the card’s left and the number on its right remain, while the text in the middle may be cut a little. The sample’s strip uses contain: the whole image shrinks in, leaving a white margin on each side.

Figure 10-5 is the arrangement of these three blocks: a three-column wall at the top, six in one row in the middle, and a block that has the third card selected on load at the bottom, with three callback panels right below the wall.

Figure 10-5 The gallery area: a three-column wall, six in one row, plus three callback panels

Each arrangement has its place. When images are only placeholders and their content isn’t read, use cover (full cell, tidy, no blank space); when the content has to be readable, use contain — not a single word can be lost. Mix two aspect ratios in one gallery and cover crops them all to the same size while contain leaves them different sizes. The first is tidy, the second complete; pick one.

There’s one more parameter, fitColumns, which defaults to true: column widths are split evenly across the container and the images follow their cells. The sample leaves it alone. Even column widths are what most cases want — six images sit neatly in the container.

gr.Gallery is interactive by default, with toolbar buttons for upload, delete, download, and so on on the block. The sample doesn’t use them: the images come from the business side, so users don’t need to upload any. Those buttons don’t affect display, and being there does no harm.

The gallery and the previous chapter’s table are alike in one way: both are handed a whole batch of things and both lay them out in cells. The difference is what each cell holds. A table holds values, a gallery holds images. Table cells can be edited; gallery cells can only be viewed (or opened larger).

Figure 10-6 Two other arrangements of the same images: six in one row, and the third card selected on load

10.6 The Selected Item and the Preview Switch

selectedIndex is “which card to show first on load”, counted from 0. The sample’s third block sets selectedIndex: 2, so as soon as the page opens the third card is in the large view.

This parameter does more than its name suggests. Omit it and the gallery is a grid; set it and the gallery opens as “one large image + a strip of thumbnails”. The large image is the selected one, the thumbnails are all of them, and below sits a row of buttons for download, fullscreen, share, and close.

            var pick = gr.Gallery(
                value: Entries(Cards),
                columns: 3,
                selectedIndex: 2,
                height: 300,
                label: "Third card selected on load");

The bottom block in Figure 10-6 is that one. Same images, same columns; one extra selectedIndex changes the whole presentation. This suits a “detail page” that lands on one image immediately and lets the user flip left and right.

allowPreview decides “whether clicking one opens it”. It defaults to true: click an image and the gallery switches from grid to large view; click the cross in the top-right and it goes back to the grid. Set it to false and clicking does nothing.

“Does nothing” is meant literally. The sample’s “six in one row” block sets allowPreview: false: click the third card and nothing on the image changes, and the three callback panels below don’t move either — not even select fires. This is the exact opposite of a table’s interactive: a read-only table blocks editing but not selection, while a read-only gallery blocks selection along with it.

Why? Because in a gallery, “selecting” and “opening” are two sides of the same thing. Click a thumbnail and the gallery first puts it in the large view, then reports “this card was selected”. Without that large-view step there is no “selected” state and nothing to report. If you want something clickable but not enlarged, this component can’t do it — you’d have to assemble an Image with buttons yourself (Chapter 11).

You can remember the three parameters this way: allowPreview governs “whether it can be opened”, selectedIndex governs “which card it lands on at load”, and columns/rows/height govern “how it’s laid out while not opened”.

Put the two switches allowPreview and selectedIndex together and three combinations show up in the sample.

allowPreviewselectedIndexOn loadClicking one
truenot setGridSwitches to large view; both select and preview_open fire
truesetLarge view + thumbnail stripSwitches the large view; only select fires
falsenot setGridNothing happens

The difference between the first and second rows is “how many events fire”. Both can be opened; one opens from the grid (two events), the other is already in the large view (only select). This table clears up one easy misconception: selectedIndex isn’t the state of “which card is selected”, it’s only “which card to show first on load”. Real selection comes from the user’s click and is reported by select.

Figure 10-7 Click the third card: the wall switches to the large view, and “Select” and “Preview open” fire together

10.7 Callbacks for Opening and Closing the Preview

The gallery has six events: select, upload, change, delete, preview_open, preview_close. The sample uses three of them, exactly the chain of “click one”, “open”, “close”.

The three events share the same signature.

string OnPick(IReadOnlyList<GalleryEntry> entries, SelectData pick)
{
    var index = pick.Index ?? -1;
    var caption = index >= 0 && index < entries.Count ? entries[index].Caption : "(no such card)";

    return $"""
        **Select** card {index} · chosen from {entries.Count} cards

        Caption: {caption}
        """;
}

The first parameter is the whole sequence of entries, not “this one”. The second, SelectData, is injected by type. The Chapter 5 rule holds here too: it takes no slot in inputs, so the binding lists only one input, [wall.Wall], while the handler function has two parameters.

The difference among the three events is entirely in that second parameter.

select brings back the index. pick.Index is this card’s position in the whole sequence, counted from 0. In Figure 10-7 the “Select” panel reads “card 2” — the third card, index 2. Use that index on entries[index] to get the entry, and the caption and path are both in hand. It reports whichever card you click; of the three events it’s the only one that can pinpoint a specific card.

preview_open brings no index. It fires when the large view opens; the first parameter is still the whole sequence, but SelectData.Index is empty.

string OnPreviewOpen(IReadOnlyList<GalleryEntry> entries, SelectData pick)
    => $"""
        **Preview open** {entries.Count} cards on the wall

        Which card was opened: it does not say (index {pick.Index ?? -1})
        """;

That panel in Figure 10-7 writes exactly this: “6 cards on the wall, which card was opened — it does not say (index -1)”. It can tell you “someone is looking”, but not “which card they’re looking at”.

preview_close also brings no index. Click the cross in the top-right and it fires once, bringing back the whole sequence of entries.

string OnPreviewClose(IReadOnlyList<GalleryEntry> entries)
    => $"""
        **Preview close** {entries.Count} cards on the wall

        Which card was closed: it does not say either
        """;

After closing, it looks like Figure 10-8. The wall goes back to a grid, the “Preview close” panel changes one line, and “Select” and “Preview open” stay where they were. Closing doesn’t undo the open; it just fires once more.

Figure 10-8 Close the preview: the wall returns to a grid, and the three panels each log their own

Figure 10-9 The three events: when they fire, what they bring back, and what to do with it

Figure 10-9 sets the three events out in three columns. The middle column is the easiest to misread: “Preview open” sounds like “the user opened the third card”, but it only says “the user opened the preview”. For “which card”, you have to record it with select first. select and preview_open fire at the same instant — select carries the index, preview_open doesn’t.

Record it where? In a state that survives across events. The sample only writes the index onto a panel, so the next event can’t read the previous value. To actually “mark this card as seen when the preview closes”, you need a variable that persists across events — that’s state in Chapter 14. This chapter first gets clear on “who carries the index and who doesn’t”.

Two more boundaries are worth stating.

One: with allowPreview: false, none of the three events fire. No preview means no preview_open or preview_close, and select is gone too, because selection follows opening. Making a read-only gallery report “which one was clicked” isn’t possible.

Which of the three to pick works backwards from “what you want to know”.

  • To know which card the user clicked, bind select. It carries the index and is the most useful.
  • To know “someone opened the preview”, bind preview_open. It has no index and only suits things that don’t need to know which card — counting, analytics, pausing other actions.
  • To wrap up after closing, bind preview_close. It also has no index; what it can do is “restore things when closed”.
  • To know “which card changed to which”, none of the three is enough. select carries one index each time, so you have to store two consecutive values and compare them. Where to store them is that same question — across events, it takes Chapter 14.

upload and delete are for galleries where users upload images themselves. An upload completing and a card being deleted each fire once, and they also bring back the whole sequence of entries. The sample’s images come from the business side, so those two events aren’t bound. change fires when the value is replaced from code. The sample’s “Switch to two” takes that route: it replaces six entries with two, and the wall shortens accordingly.

10.8 Chapter Summary

Charts have two routes. Plot is passthrough: PlotData(library name, JSON), with the name one of four (plotly, bokeh, altair, matplotlib) and the JSON that library’s own drawing — the component doesn’t interpret a single byte. It’s flexible, but coordinates, colors, and aggregation all have to be computed yourself; a wrong library name or a wrong JSON key leaves the chart area empty, with no error.

NativePlot draws directly. Give it a “column name → values” dictionary, say which columns x, y, color take, and the component computes the rest. The three factories LinePlot, BarPlot, ScatterPlot share one parameter list and differ only in mark: line, bar, point. Column types are inferred from values — numbers are quantitative, dates temporal, everything else categorical; Booleans count as numeric and empty columns as categorical. Dates are sent to the front end as milliseconds, so the tooltip shows an extra eight-hour time-zone offset.

color is grouping: a line chart splits by it, one line per group, and a group with a single point can’t form a line. yAggregate has three settings — sum adds, count counts entries, mean takes the average — three questions over one column. count requires y; omit it and the chart area goes empty. xBin cuts a numeric column at a fixed bin width; it gives the width, not the bin count.

title, xTitle, yTitle, colorTitle are plain text. xLim, yLim are display ranges: points outside aren’t drawn, but the data isn’t gone. xAxisFormat changes only how dates are written, not tick spacing; when labels crowd, tilt them with xLabelAngle. tooltip defaults to "axis", listing a whole point’s values across all columns on hover. height is the block height; smaller than the chart’s own height and the bottom gets clipped. Clearing the charts returns empty values and all six go blank together.

Gallery’s value is a sequence of entries; an entry can be a path, a URL, bytes, a stream, or “image + caption”. columns sets how many per row, rows the maximum rows, height the block height — the three together decide how big each cell is. objectFit decides how an image fits its cell: cover crops to fill, contain leaves margins.

selectedIndex is which card to show first on load; set it and the gallery opens as “one large image + a thumbnail strip”, not a grid. allowPreview decides whether it can be opened; set it to false and clicking does nothing, not even firing select. In a gallery, selecting and opening are the same thing.

All three events bring back the whole sequence of entries. select adds an index (counted from 0) that pinpoints a specific card; preview_open and preview_close have an index of -1 and only say “opened” or “closed”, not which one. For “which card”, you have to record it with select, in a state that survives across events — that’s for a later chapter.

What’s in the charts and the gallery can’t be saved either. Refresh and the six charts go back to their initial data, the gallery back to six cards. The two swapped-in images and the opened preview all live on the page and don’t persist. Saving has to wait for state in Chapter 14.

The next chapter switches to heavier content: images, audio, video, and 3D models, each with their own sources, types, and formats.

Chapter 11. Media Components

The charts and galleries in the previous chapter deal with numbers already computed and images that already exist. This chapter switches to things the browser produces itself: a photo, a recording, a video, a 3D model.

These values differ from the earlier ones in one fundamental way: there is a file behind each of them. Where the file comes from, what the handler function receives, and what format it is written back as — every one of these has to be spelled out, and each has its own set of switches; mixing them up causes errors.

The example adds two blocks to the workbench. The image block holds two input images, an editor, and a composite image; the audio/video block holds a piece of audio, a video, and three models. The assets all ship with the example: an illustration, a marker image, a prompt tone a little over two seconds long, a three-second clip, and a sphere model.

11.1 Image Input Sources and Data Types

Two parameters in Image’s parameter list decide the whole contract; the rest only control appearance.

                fromPath = gr.Image(
                    value: MediaBook.Photo,
                    sources: ["upload", "webcam", "clipboard"],
                    type: "filepath",
                    height: 260,
                    label: "Path image: three sources, the handler function receives a path");

                fromBitmap = gr.Image(
                    value: MediaBook.Mark,
                    sources: ["upload"],
                    type: "numpy",
                    height: 260,
                    label: "Bitmap: upload only, the handler function receives pixels");

sources controls “where it comes from” and type controls “what gets passed”. Remembering these two statements separately is more useful than memorizing the parameter names. Figure 11-1 lays the two parameters out as two axes. The left column lists the three entry points of sources, the right column lists the two results of type, with the component in the middle.

Figure 11-1 The two parameters of Image: one controls where it comes from, one controls what gets passed

sources has three values. upload picks a file or lets you drag one in, webcam opens the camera to take a picture, and clipboard pastes from the clipboard. Leave it out and all three entry points are provided. Write only upload and the block is left with upload alone. In the example the “path image” carries three entry points, while the “bitmap” has only one.

type has three values, but in C# they come down to only two kinds of thing.

  • numpy and pil. The handler function receives a RasterImage, with width, height and RGBA pixels all in hand;
  • filepath. The handler function receives a string, the path of that file in the cache directory.

You can compute the byte count of a bitmap yourself. Multiply width by height by four; the four channels are red, green, blue, and alpha. The example’s marker image is 200×200, so 200 × 200 × 4 = 160,000 bytes. It has nothing to do with file size. The same image saved as png is 1,011 bytes, yet the handler function receives 160,000 bytes. What the bitmap route buys you is “pixels already in memory”, and the price is size.

You write the handler function’s signature according to type.

string ReadImages(string? path, RasterImage? bitmap)
{
    var fromPath = string.IsNullOrEmpty(path)
        ? "(empty)"
        : $"{MediaBook.Describe(path)}\n\nLocation in the cache: `{path}`";

    var fromBitmap = bitmap is null
        ? "(empty)"
        : $"{bitmap.Width}×{bitmap.Height} · {bitmap.Pixels.Length} bytes";

    return $"""
        **Read images**

        Path image: {fromPath}

        Bitmap: {fromBitmap}
        """;
}

Both parameters are nullable, because both images can be empty. Click “Clear images” and read again: both parameters are null, and the panel reads “(empty)”. The empty value is part of the contract. No image means no image, and the handler function has to decide on its own what to return in that case. The example’s choice is to write “(empty)” into the panel, so that emptiness is visible.

What you can give value is not limited to a path. An existing image (a RasterImage), a byte array, or a stream can all serve as the initial value; the example gives a path, because the assets are files that ship with the program, and passing one to the component as the initial value is the least work. After the component gets the path, it copies the file into the cache directory and sends the address of that cached copy to the front end. So the address shown in the UI is not the same as the path supplied by the business side.

Figure 11-2 shows what it looks like after you click “Read images”. The path image reports photo.png · 2217 bytes · .png, and the bitmap reports 200×200 · 160000 bytes.

Figure 11-2 Read images: the path image brings back a cache path, the bitmap brings back width, height, and byte count

You have to read these two numbers together. The illustration in the example is 480×320. As a file it is 2,217 bytes; as pixels it is 614,400 bytes. Click “Swap image” and the bitmap block switches to the illustration; read again and you get this number. 2,217 is the compressed file, 614,400 is the pixels of 480 × 320 × 4 bytes. The two measurements are two different things.

Under the right-hand image in Figure 11-2 there is only one line, “Drop an image file here to upload”; under the left-hand one there are three icons in a row. The difference is that sources is missing two values. Buttons follow the values: an entry point with no value does not appear.

Each of the three entry points maps to one browser capability. Upload is a file picker, the webcam needs user permission, and the clipboard needs the page to be granted paste permission. If permission is not granted, the entry point will not open; that is the browser enforcing the rules. When you write sources, narrow it to the situation at hand. A form that only allows upload but leaves the webcam and clipboard on as well is just giving the user two extra paths that will fail.

The entry points do not accept everything either. Push an audio file into the image block and the front end stops it on the spot, popping up Invalid file type: tone.wav. Only image/* allowed. in the top-right corner; the value in the block does not move. Figure 11-3 shows exactly that. The audio block behaves the same way. Feed it a text file and the message changes to “Only audio/* accepted”, followed by a long list of the types it recognizes.

Because it is stopped at the front end, the server never receives this upload at all, and the handler function knows nothing about it. This is the same type boundary discussed in Chapter 3. The error is in the type, the value does not change, and the UI states the reason. Skip this step and the consequences are reversed: the file lands in the cache, the handler function gets a path it cannot open, and it becomes unclear whose fault the error is.

Figure 11-3 Wrong type: the front end rejects it on the spot, the value in the block does not move

“Swap image” and “Clear images” follow the old route from Chapter 3. The handler function returns a new value, or returns null. The component changes along with it; events are not involved.

11.2 Image Format, Size, and Streaming

format defaults to webp. This parameter controls exactly one thing: which format to use when writing pixels to a file. The example’s composite-image block sets format: "png".

                composite = gr.Image(type: "filepath", format: "png", height: 320, interactive: false,
                    label: "Composite image: written back as png");

When the value is an existing file path, format has no say. The composite image that the editor passes to the handler function is already png, so the component sends it to the front end unchanged and the file is still called composite.png. Only if you replace this block’s value with a bitmap (type: "numpy") will the component write a fresh file according to format, named image.png.

Keep these two things distinct. The incoming file lands in the cache as-is, byte for byte unchanged; only if what goes out is a pile of pixels does the component write a file for you, and that is when format has the final say.

The default webp is a sensible choice: small, with transparency, and recognized by every browser. If another program is going to use it next, png is safer. It is lossless, and there is no “how lossy should it be” parameter to tune. The example’s composite image writes png, because the next step may be to print it or edit it again; webp would look fine too, except that every save adds another layer of compression.

height and width are the dimensions of the block, in pixels. The example’s two input images set 260, the editor sets 320. They are not the pixel dimensions of the image. Put a 480×320 image into a block 260 high and the image is scaled down proportionally into the block, aspect ratio unchanged. Fix the block height while the image’s ratio does not match and you get either letterboxing or cropping — the same thing as objectFit in the Chapter 10 gallery.

Letterboxing or cropping: Image has no switch like objectFit; it works on a “fit it all in” basis. The whole image is shrunk into the block and the spare space is left blank. In the left-hand block of Figure 11-2 the image is a 480×320 landscape picture, the block is 260 high and nearly four hundred wide, so a white strip is left on each side. To make the image fill the block you have to set the block’s aspect ratio to the image’s ratio. The block is a container, not a picture frame.

On Image, interactive controls “whether you can put things into it”. The composite-image block sets interactive: false, so there is no upload entry point on the block, just an image. It is an output slot; nobody should be dragging files into it. The input block leaves it out, so by default things can be put in. An input component with no interactive counts as interactive — this is the Chapter 4 rule carried over to media components.

streaming is another switch, false by default. Set it to true and the default for sources changes: no longer three entry points, only the webcam remains. The webcam then sends frames to the server one by one, firing a stream event for each frame that arrives. The example does not enable it, because there is no webcam on this machine to shoot with; to try it, change one input image to streaming: true, swap the handler function for one that takes a RasterImage, and the UI shows a live feed.

The contract for this mode differs from the previous two. The stream event’s handler function is called once per frame, and the RasterImage is that single frame, not a whole video. In other words, the handler function paired with streaming input must return within one frame and can only do lightweight checks. Run heavy work on every frame and the UI grinds to a halt. None of the example’s handler functions that run once per button click are suitable for hanging off this.

Streaming input is not the same as the streaming output of Chapter 16. Here what streams is the input, and the handler function is called repeatedly; there what streams is the return value, and one call produces many outputs. The two share a word; do not mix them up.

streaming has one more side effect. Once it rewrites sources, the upload and clipboard entry points are gone. If you want both “take a picture” and “live view” at the same time, you have to place two components: one ordinary, one streaming, each handling one thing.

Figure 11-4 draws the two legs a media value travels on the server. The incoming leg is “move”: the bytes the browser uploads land in the cache directory as-is, with the file name and extension unchanged. The outgoing leg is “write”: if what the handler function returns is not yet a file, the component writes a fresh one according to format.

Figure 11-4 The two legs a media value travels: in is move, out is write

Both legs land in the same directory. When that directory is cleared and how large it can grow is what the file mechanism in Chapter 12 governs; this chapter only uses the layer where “a file sits behind the value”.

11.3 ImageEditor Transforms and Layers

ImageEditor is a heavier version of Image: on a background image you can draw with a brush, erase, crop, and add layers. Its value is three images.

                editor = gr.ImageEditor(
                    value: MediaBook.Photo,
                    type: "filepath",
                    transforms: ["crop", "resize"],
                    height: 320,
                    label: "Editor: brush, eraser, layers");

The handler function receives an EditorValue, with three fields. Background is the base image, Layers are the layers drawn on top of it, ordered from bottom to top, and Composite is the one the user sees — the base image plus all the layers.

The types of these three fields follow type. The example’s editor sets type: "filepath", so all three are paths; leave out type and the default is numpy, so all three are RasterImage. One component passes three images to the handler function at once, and type governs all three at once.

transforms decides which transform tools appear in the toolbar. Write ["crop", "resize"], click the “Image” button on the toolbar, and what expands are the two items Crop and Resize; write only ["crop"] and the resize item does not appear. Leave it out and the default is still these two items. Cropping and resizing are the two things you do most often when editing an image.

Cropping is done by dragging a box; once the box is set, a “Confirm crop” button appears on the toolbar, and only clicking it actually cuts. Skip that click and the box stays but the image is unchanged. Both transforms modify the base image, and the modified base image is Background.

(string, object) ApplyEdit(EditorValue value)
{
    var report = $"""
        **Edit** layers {value.Layers.Count}

        Background {Size(value.Background)} · Composite {Size(value.Composite)}
        """;

    return (report, value.Composite!);
}

Figure 11-5 shows the state after one stroke is drawn. The toolbar is a column on the left; from top to bottom it is Image (base image and transforms), Brush, Eraser, Color, Brush size, and the Layers toggle. The top three buttons are one group. Click “Image” to expand crop and resize, click Brush to enter drawing mode, click Eraser to enter erasing mode. Only one is active at a time, and the selected one gets a darker background.

The bar at the bottom reads “Layer 1”, the current layer. When you do not name one, the editor supplies a layer called Layer 1. There is another toggle on the right of the layer bar; click it to open the layer list. The example has only one layer: draw one stroke and Layers goes from 0 to 1. An empty layer does not count; only one with something drawn on it does.

The benefit of the layer design is that “you can undo a mistake”. Annotations go on a separate layer, the base image stays put, and erasing a layer returns things to the original. Layers is ordered bottom to top, with the first element the lowest layer; Composite is what those layers look like stacked in order, so reading it saves you from compositing them yourself.

Figure 11-5 One stroke in the editor: toolbar on the left, layer bar at the bottom

Brush and Eraser are each a set of options; leave them out and the defaults are used. Eraser has one default_size, Brush has five colors with red as the first. The example does not set them, so it uses the defaults and that stroke is red. layers can be turned off too. Write false and the layer button disappears, leaving only a base image.

After drawing, click “Apply edit”: the handler function gets the EditorValue, the panel reads “layers 1”, the background is background.png · 6927 bytes, and the composite is composite.png · 7980 bytes. The composite is a little larger than the background; the extra is that stroke.

Figure 11-6 Apply edit: the composite image lands on the right, the values report the layer count and two files

The “composite image” on the right is Composite. It is returned by the handler function and takes the ordinary output route. The first return value of ApplyEdit is written into the panel, the second into the image block. This step is the same as the multiple return values discussed in Chapter 3, except that here what is returned is an image.

You can keep using the edited result. Click “Back to editor”.

string BackToEditor(string composite) => composite;

The handler function writes the value of the composite-image block straight back into the editor, and the editor treats it as the new base image. That stroke turns from “a drawing on a layer” into “part of the base image”; keep drawing on top and you are drawing a second layer. This works because the editor is set to type: "filepath". The composite image is a path, and a path written back into the same component is recognized.

The chain goes like this. The editor produces an image, the image block catches it, then feeds the path back into the editor, so “the edited result” becomes “the starting point for the next round”. No state is needed in between, no extra storage either; the value just keeps passing between the two components. In a product this is the least-effort way to “keep editing on top of existing annotations”.

The editor also has a canvasSize, 800×800 by default, which is the pixel size of the canvas; fixedCanvas decides whether an uploaded image is shrunk onto the canvas or the canvas is stretched to the image’s size. The example leaves both alone. The base image is 480×320 and the canvas follows the image; a canvas larger than the image is no easier to use. You only need to hard-code these two when you want a fixed board for people to draw on (say, a signature pad of uniform size).

EditorValue is an output-only type. It has no public constructor; the handler function can read it but cannot construct one itself. To push a value back into the editor, you push an image or a path, not an EditorValue.

11.4 Audio Input Sources and Recording

Audio follows the same idea as Image. sources controls where it comes from, type controls what gets passed, and format controls what is written back.

            var audio = gr.Audio(
                value: MediaBook.Tone,
                sources: (object)new[] { "upload", "microphone" },
                type: "numpy",
                format: "wav",
                editable: true,
                waveformOptions: new WaveformOptions
                {
                    WaveformColor = "#1d4ed8",
                    SkipLength = 25,
                },
                label: "Audio: upload or record, waveform is draggable");

sources has two values, upload and microphone. Leave it out and both are provided; with streaming: true only the microphone remains, the same rule as for Image. The example provides both, so the block has two entry points underneath, one for upload and one for recording. Write only upload and the record button does not appear. As on the image side, entry points follow the values.

The values of type are numpy and filepath, and the values of format are wav, mp3, or empty. The three parameters have the same names as on Image, and their meanings are carried over too: one controls what gets passed, one controls the format written back. The differences are in the details, covered in the next section.

recording is another entry-point switch, false by default. Set it to true and the component opens the microphone as soon as it loads and sits in a ready-to-record state, so the user does not have to click an entry point first. That suits an interface that “opens as a voice recorder”; it does not suit a default page. A permission prompt the moment the page opens makes many people refuse on instinct. The example uses the default. Give it a ready-made piece of audio, so arriving shows a waveform first, which is friendlier than a permission dialog.

Recording is not a single click. Click the record entry point, a device list appears first, choose a microphone, then click “Record”, and when you are done speaking click “Stop”. Once that sequence finishes, startRecording and stopRecording each fire once, and the recorded audio becomes the component’s new value. The example binds both events, so the panel logs one line at the start and one at the stop. First it reads “Recording started; click Stop when done”, and after stopping it changes to “Recording audio.wav · 222306 bytes · .wav”.

The recorded file is named audio.wav, with the extension following format. A roughly three-second mono recording is over two hundred thousand bytes. Wav is uncompressed, so the size is simply that substantial. To make it smaller you have to convert to another format before writing the file; the component does not do it for you.

Recording needs a microphone and browser permission too. If permission is denied, the record entry point will not open, and the UI will not conjure up a fake audio file. This is the same kind of thing as “unsupported format”: if it cannot be done, say so plainly, do not pretend it was done. The same holds when the machine has no microphone: the device list is empty and clicking “Record” does nothing.

Playback is another set of events. The example binds play and stop.

    played.Audio.Play(OnAudioPlay, [played.Audio], [played.AudioReport], apiName: "Audio play");
    played.Audio.Stop(OnAudioStop, [played.Audio], [played.AudioReport], apiName: "Audio stop");

Click Play and the waveform fills with color from left to right, the time goes from 0:00 to 0:01, and the panel reads Play tone.wav · 105884 bytes · .wav. What the handler function receives is the path of this audio, not sample data. Figure 11-7 shows playback at one second.

Figure 11-7 Audio playback: the waveform has moved through a stretch, the panel notes this file

stop does not fire on every click the way play does. Reaching the end does not fire it; only clicking “Reset” fires it once, and the panel changes to “Stop”. These are two different things. Finished playing is finished playing, stopped is stopped, and the component only reports the latter. To handle “played to the end” you have to watch the time reach the end, or compute it yourself from playbackPosition and the duration; this chapter does not go into it.

pause is the third event, and the example does not bind it. Its difference from stop is semantic. Pause means “stop here and resume later”, stop means “go back to the start”. To record “where the user listened up to”, bind pause; to record “this pass is finished”, bind stop.

The handler functions of all three events accept a string, the path of this audio. Not sample data, not the duration. You have to read the duration from the file yourself. The example’s panel prints only the file name and byte count, because those are enough to show that “the event really did arrive with a value”.

11.5 Audio Waveform and Format

The waveform is the main appearance of this block, and its parameters all live in waveformOptions.

WaveformColor is the color of the waveform; the example gives it blue, and the already-played stretch switches to another color on its own, no extra setup needed. SkipLength is how far the rewind and fast-forward buttons jump in one go, in percent. The example writes 25, this clip is 2.4 seconds, so the two arrow buttons’ tooltips read “Skip 0.6 seconds”. Write 10 and it jumps 0.24 seconds, write 50 and it jumps 1.2 seconds.

ShowRecordingWaveform decides whether a live waveform is drawn while recording; by default it is. The reason you can see the loudness during recording comes down to this. SampleRate is the sample rate of the waveform, 44100 by default; lower it and the waveform gets coarser, while the audio itself is unaffected.

The waveform itself has three color segments: the part not yet played, the part already played, and the part drag-selected ready for trimming. The example only configures WaveformColor, and the played segment changes color automatically, so in Figure 11-7 the left is orange and the right is blue. All three colors can be configured separately; TrimRegionColor is the selection one, and since the example does no trimming it goes unused.

editable decides whether the user can trim and edit. The example writes true, so the toolbar has “Trim” and “Reset”; write false and the user can only play, not change this audio. The trimmed result is also a new value for this component and can be passed straight to the handler function.

The values of format are wav, mp3, or empty. It governs output only. When the handler function returns a piece of audio, the component writes a file in that format. The example writes wav, so stopping a recording saves audio.wav. This “write by format” does not include transcoding. The framework does not run external programs; writing mp3 will not turn wav into mp3 either — a wrong format simply means a wrong file. To convert, you have to do it yourself before passing the audio to the component.

Writing empty (leaving this parameter out) means “leave it alone”. Whatever file the handler function returns is sent to the front end unchanged. Upload an mp3 and return it as-is: empty is the least effort; when the path runs all the way from recording, writing wav is more explicit.

A separate word about type: it says numpy, yet the handler function receives a path.

string OnAudioPlay(string? path)
    => path is null ? "**Audio** no value." : $"**Play** {MediaBook.Describe(path)}";

The signature says string, and what gets printed on the panel is a path like C:\...\tone.wav. The reason is not complicated. Decoding audio into a sample rate and a sample buffer requires a decoder that can handle the various browser recording formats, and libraries of that kind almost all call external programs. The framework does not do this, so on audio the value numpy only means “it knows you want samples”; what actually reaches the handler function is still a path. Writing filepath gets you the same thing. On audio the two spellings make no difference.

This is a boundary the component draws for itself. Pixel-level processing of audio you do yourself; the component only guarantees that “where the file is” is reliable. For waveform data, a spectrum, or silence detection, start from that path and read it with a decoding library of your own choosing.

playbackPosition sets which second playback starts from, 0 by default; loop makes it restart automatically after finishing; autoplay makes it play on arrival. All three are pure playback behavior and do not affect the value. autoplay is blocked by the browser’s autoplay policy. If the page has had no user interaction, no sound plays — that is the browser’s doing, not a component problem. The example leaves all three alone: the audio comes in stopped at 0:00, waiting for someone to click Play.

11.6 Video Sources, Subtitles, and Playback

The parameter list of Video closely resembles Image, with three extra things: subtitles, playback position, and the audio track.

            var video = gr.Video(
                value: MediaBook.Clip,
                playbackPosition: 1,
                height: 300,
                subtitles: new[]
                {
                    new Subtitle { Start = 0.4, End = 1.6, Text = "Sentence one: four squares from left to right" },
                    new Subtitle { Start = 1.7, End = 2.9, Text = "Sentence two: the subtitles are written as a vtt file" },
                },
                label: "Video: starts at second 1, with subtitles");

sources provides upload and webcam by default; the example does not set it, so the block has two entry points, “Upload” and “Webcam”. streaming is off by default; turn it on and the component plays a stream produced piece by piece by the handler function, which is a Chapter 16 matter.

subtitles accepts a path, or a series of Subtitle items. The example gives the latter. Each item has three fields: start second, end second, and text. This list of entries is not sent to the front end as-is. Browsers only understand WebVTT, so the component first writes them into a subtitles.vtt file in the cache, then has <video> attach that file. The line of text you see in the UI is displayed by the browser itself, according to the time.

Each of the two forms has its use. If you already have a finished subtitle file, give the path directly and the component attaches it unchanged; if the subtitles are computed from data (say, generated from timestamps), giving a list is less work. You do not have to land a file first, nor hand-write the WebVTT header. The example is the second form. The two sentences sit in the code, and their times line up with that three-second clip.

The time unit is seconds, and decimals are allowed. The example’s first entry runs from 0.4 seconds to 1.6 seconds, the second from 1.7 seconds to 2.9 seconds. A 0.1-second gap is left in between, so the two lines do not overlap when switching. That gap is not required, but with it the speech feels more human.

Figure 11-8 shows it during playback. The video starts at second 1. That is what playbackPosition: 1 means: on arrival it does not play from the beginning, it stops directly at second 1. Click Play, and when it reaches a little past two seconds the bottom of the frame switches to the second subtitle.

Note that “stop at second 1” and “start playing from second 1” are two different things. playbackPosition only moves the position; it does not press Play. On arrival the example is a still frame with the time 0:01 / 0:03, and nothing moves until you click. To play on arrival you have to add autoplay: true, and autoplay is blocked by the browser. A page with no user interaction plays no sound. So “start in the middle and wait for a click” is the steadier default.

Figure 11-8 Video playback: starting at second 1, the second subtitle sits at the bottom of the frame

The subtitle position is decided by the browser, hugging the lower edge of the frame. Make the block taller and the frame larger and the text grows; make the block short and the text shrinks. The example fixes the block height at 300, so the subtitles are legible but not large. To make them larger you have to draw your own subtitle band outside the frame, which is a different matter.

The control bar also comes with the viewer: play/pause, progress, time, volume, fullscreen. It appears when the mouse rests on the frame and hides itself a moment after you move away. There is no control bar in Figure 11-8 precisely because the mouse was moved away before the screenshot. For subtitles to stay visible, the control bar must not sit on top of them. In a product you need not worry about this; the user will make it appear on their own.

Three events follow playback: play, pause, and end. The example binds all three, and the panel writes “Play”, “Pause”, and “Playback finished” respectively. The line in Figure 11-8 is Play clip.webm · 79168 bytes · .webm; at the end of playback the same line changes to “Playback finished”.

    played.Video.Play(OnVideoPlay, [played.Video], [played.VideoReport], apiName: "Video play");
    played.Video.Pause(OnVideoPause, [played.Video], [played.VideoReport], apiName: "Video pause");
    played.Video.End(OnVideoEnd, [played.Video], [played.VideoReport], apiName: "Video end");

On video, format is likewise “the container used when writing the file”, not a transcoder. The example’s asset is webm, which browsers can play directly, so it passes through unchanged. Switch to a container browsers do not recognize, such as avi, and writing format as mp4 will not rescue it. The component will not convert for you; convert it yourself before passing it to the component.

includeAudio follows sources by default: for videos that can be uploaded, the audio track is kept; for videos recorded from the webcam, there is no audio track to keep in the first place. loop and autoplay are each a boolean — the former restarts after finishing, the latter plays on arrival. Autoplay is blocked by the browser’s policy, and being blocked raises no error; there is simply no sound.

Think carefully about putting loop and the end event together. With looping on, reaching the end fires end once and immediately starts again from the beginning. If you want to do something “when one round ends” (log a line, switch to the next clip), looping makes that happen over and over. The example does not enable looping: playback stops on the last frame, the panel writes “Playback finished”, and you can see at a glance that it has reached the end.

When the container is not recognized, the block is just an empty frame and clicking does nothing. It is the same principle as a wrong image path. When the error is in the file, the UI shows only “nothing there”. Video runs into this especially often, because different browsers support different containers. mp4 is the safest, webm is fine on newer browsers, and avi is basically out of the question. The example uses webm because the asset was itself recorded by a browser, so the container matches.

11.7 Model3D Display Modes and Camera

Model3D is the quietest component in this chapter. It accepts no upload, only a path, and sends the model path to a viewer in the browser to be drawn. The block has only two buttons, Undo and Download; there is no “swap the model” entry point, and where the model comes from is the application’s business.

                solid = gr.Model3D(
                    value: MediaBook.Model,
                    displayMode: "solid",
                    cameraPosition: new double?[] { 45, 30, 2.4 },
                    height: 220,
                    label: "Solid");

                cloud = gr.Model3D(
                    value: MediaBook.Model,
                    displayMode: "point_cloud",
                    clearColor: new double[] { 0.06, 0.09, 0.16, 1 },
                    cameraPosition: new double?[] { 45, 30, 2.0 },
                    height: 220,
                    label: "Point cloud");

                wire = gr.Model3D(
                    value: MediaBook.Model,
                    displayMode: "wireframe",
                    clearColor: new double[] { 0.06, 0.09, 0.16, 1 },
                    cameraPosition: new double?[] { 45, 30, 2.4 },
                    height: 220,
                    label: "Wireframe");

displayMode has three values. solid draws the faces, point_cloud draws only the vertices, wireframe draws only the edges. The same model file gives different information in the three modes. Solid shows shape and color, point cloud shows vertex distribution, wireframe shows mesh structure. Figure 11-9 places the three in a row.

Figure 11-9 The three display modes: solid, point cloud, wireframe

The point cloud mode has a prerequisite: the vertices must be dense enough. A cube has only twenty-four vertices, and in point cloud mode that is twenty-four nearly invisible dots, which amounts to nothing; switch to a sphere with over three hundred vertices and the point cloud becomes a mesh whose shape you can make out. displayMode does not change the model itself, it only changes how it is drawn. Whether that way of drawing shows anything depends on how much the model has to draw.

How to choose among the three depends on the question you want to answer. To see what the finished product looks like, use solid; to inspect mesh density and find broken faces, use wireframe; to look at a scanned point cloud and its vertex distribution, use point cloud. Opening three blocks side by side for the same model is easier to compare than switching modes back and forth. Figure 11-9 is arranged exactly that way.

clearColor is the color behind the model, four numbers: red, green, blue, and alpha, all between 0 and 1. By default all four are 0, which is fully transparent. Whatever color is beneath the block, the model appears to float on that color. The example gives the point cloud and wireframe a dark background, because light points and lines are hard to see on a light background; the solid one keeps transparency and follows the page.

The alpha dimension can be used on its own. Write the fourth component as 0.5 and a semi-transparent color block appears behind the model, with the page background still showing through. Write 1 and it is opaque, so the block becomes its own canvas. In Figure 11-9 the two on the right are 1, and the one on the left is the default 0.

cameraPosition is the camera’s position, three numbers: two angles and one distance. The first two are the horizontal angle and the pitch angle, in degrees; the third is how far the camera is from the model. Any of the three can be left out (written as null), and the one left out is decided by the viewer itself. The example writes all three. The angles are the same and the distances differ slightly, so the three images share one viewpoint but differ a little in size.

The distance number depends on the model’s size. The example’s sphere has a radius of 0.8; at a distance of 2.4 the sphere fills two thirds of the block height, and at 1.6 it is right in your face. Switch to a model of very different size and this number has to be adjusted along with it. It is a real distance.

To change only the distance and leave the angles alone, write new double?[] { null, null, 2.4 }; writing all null is the same as omitting the parameter entirely, and the camera parameters keep the viewer’s defaults. The example writes all three so the three images share one viewpoint. Write only one and the other two each follow their own defaults, so side by side they look like three different models.

zoomSpeed and panSpeed are the sensitivity of mouse operations, both 1 by default. Scroll to zoom, drag to pan; turn them up and they feel more responsive, turn them down and they feel steadier. The example leaves them alone. With three blocks side by side, the sensitivity has to be the same so they do not interfere with each other.

The viewer comes with its own set of mouse operations: drag to rotate, scroll to zoom in and out. These operations do not go through the server and do not change the value. After you rotate, the handler function knows nothing about it. If you want “which angle the user rotated to”, this component cannot give it to you; it is a viewer, not an editor. To make a model editable you have to build your own.

The model file itself is not validated. Give it a file that is not glb and the component still accepts it; the browser just cannot draw it, so the block is empty — the same principle as giving Image a path that does not exist. When the error is in the file, the UI shows only “nothing there”.

11.8 Chapter Summary

Two parameters of Image decide the contract. sources controls where it comes from, with three values: upload, webcam, clipboard; leave it out and all three are provided, and with streaming: true only the webcam remains. type controls what gets passed. numpy and pil give the handler function a RasterImage (width, height, RGBA), filepath gives a cache path. The same 480×320 image is 2,217 bytes as a file and 614,400 bytes as pixels.

format only governs the leg where pixels are written to a file; when the value is an existing path it has no say, and the file is sent to the front end unchanged. height and width are the dimensions of the block, not the pixel dimensions of the image. interactive: false removes the upload entry point — an output slot should not let people drag things into it.

The value of ImageEditor is an EditorValue. Three parts — base image, layers, composite — whose types follow type. transforms decides which transforms appear in the toolbar; brush, eraser, and layers decide what those tools look like. Draw one stroke and layers go from 0 to 1; after applying, the composite image is the new output, and writing its path back into the editor makes the edited result the new base image.

For Audio, sources is upload and microphone, and recording: true opens the microphone as soon as it loads. play fires on playback, stop fires on stopping; reaching the end does not fire stop. Recording needs a microphone and permission, and startRecording and stopRecording each fire once. The waveform is governed by waveformOptions: color, skip ratio, recording waveform, sample rate; editable decides whether trimming is allowed.

On audio, type set to numpy still gets a path, because decoding needs external programs and the framework does not do it. format only takes effect when writing the file, and it does not transcode.

For Video, sources defaults to upload and webcam, playbackPosition sets which second to start from, and giving subtitles a series of Subtitle items writes them into subtitles.vtt and attaches that to <video>. The three events play, pause, and end follow playback. format likewise does not transcode, and cannot rescue a container the browser does not recognize.

Model3D accepts only a path, displayMode is one of three — solid, point cloud, wireframe; clearColor has four components between 0 and 1, fully transparent by default; cameraPosition is two angles plus a distance, any of which can be left out. A point cloud needs dense enough vertices before its shape shows.

Look at the four components together and the structure is the same one. sources controls the entry points, type controls what gets passed, format controls what is written back. Image breaks these three things down the finest, audio and video copy it, and the model keeps only the first. It accepts no upload, only a path. Once the structure is fixed, when you meet a new media component, look for these three parameters first; it is faster than memorizing the parameter list one by one.

Behind every media value is a file. The file lands in the cache directory, in is move and out is write; when that directory is cleared and how large it can grow is covered in the next chapter. The next chapter also fills in the things this one skirted around: one file, multiple files, upload destination, size limits, and download.

Chapter 12. Files and Temporary Files

The images, audio, video, and models in the previous chapter all have a file behind them. This chapter puts the file itself at the center. It does not care whether it is an image or a recording, only where it comes from, where it lands, and when it disappears.

A file value is unlike every earlier value. A number sent to the server with a request is that number, and it is gone once used; what a file sends with a request is only the name of “some file somewhere”, while that file still sits on disk, where it can be read by others, deleted by the cleanup routine, or overwritten by the next upload. What the handler function gets is that name, not the file itself.

The difference runs deeper than one layer. Numbers and strings are “values”: copy one, pass it to someone else, store it in a database, and it is still that content; a file is a “reference”: what gets passed is an address, and the content stays where it is. Whether a file “still exists right now”, “who has the right to send it to others”, and “when it will be cleaned up” are all decided by this application’s configuration; the handler function holds only that name.

There is one more consequence. A file is the only kind of value that “can still change after being sent to the front end”. A number the handler function computes does not change on its own, but the file pointed to by the path the handler function received may be deleted by the cleanup routine two minutes later, or replaced with different content by the next upload. If two uploads have the same content hash, the path does not even change. This chapter is about “who manages a file’s lifecycle”.

Broken down: how many files are allowed (fileCount), what is passed to the handler function (type), and which types are allowed (fileTypes). Add four knobs on top: which directory files land in, how large they can be, how often the cache is cleaned, and which directories beyond the cache may be served. The example adds a tenth block to the workbench, the file module, which lays all of these out at once.

12.1 File Count and Type Limits

File is the main component of this chapter; its parameter list is short, and the first three decide the contract.

                one = gr.File(
                    fileCount: "single",
                    fileTypes: [".txt"],
                    type: "filepath",
                    height: 240,
                    label: "Single file (path): txt only");

fileCount has three values: single for one file, multiple for several, directory for a folder. It governs “how many are allowed”, but this parameter also changes the look of the UI along the way, more than you would expect. Figure 12-1 places the three modes side by side: how many each allows, what the entry point is, what structure is passed to the handler function, and which mode alone has handles and deletion.

Figure 12-1 The three values of fileCount and the structure each passes to the handler function

The single-file mode has no delete button and no reordering handle. With only one file, deleting leaves it empty, and there is nothing to reorder. Only the multiple-files mode needs these. Figure 12-2 shows the example after “Load a group” has been clicked: three files in a column, each row with two small dots on the left as a drag handle, 438.0 B plus a downward arrow on the right, and deletion at the far right.

The three modes are not just a switch for “how many are allowed”; they correspond to three different UI intentions. Single file means “exactly one, no more”: changing an avatar, uploading one config file, naming one output directory — the user has one thing in mind, and giving one more is a mistake. Multiple files means “a batch”: several logs to merge, several images to print together, where order may matter, so handles are needed. Directory means “a whole package”: the source files of an entire project, a complete set of assets, where the user does not want to pick one by one, and the folder itself is the unit they want to express.

The cost of picking the wrong mode is not paid at compile time, it is paid by the user. Write an input meant for a batch as single file and the first file is quietly replaced when the user drags in a second one, with no notice at all; write an input meant for one file as multiple files and the handler function has to decide on its own “which one to use when three are given”, a decision the UI should have made.

fileCount also has a side effect that is easy to miss: it decides how the block’s height grows. A single-file block has a fixed height: set height: 240 and it is 240, taking up that much even when empty; a multiple-files block grows with the number of rows — three files give the height in Figure 12-2, ten files hit the height limit and then scroll internally. Place two blocks side by side and this difference keeps them from lining up. The example gives the two single-file blocks the same height precisely to align them; the row with a group of files and a directory each sets 230 for the same reason.

Figure 12-2 A group of files: handles, byte counts, download, and delete all on the row

The handle appears only when allowReordering: true is set. The example’s three files set this parameter, so they can be dragged into a new order; remove that line and the handle disappears, and the order is fixed in the array. This switch takes a boolean, but it decides “whether the user can change the order”, and that order directly determines the array order the handler function receives. It is not decoration.

fileTypes is the second parameter; it accepts a list of extensions or categories, and writing [".txt"] means accepting text only. It has two effects, one visible and one hidden. The visible one writes the extension into the browser’s file picker, so the user only sees txt when it opens; the hidden one is that the front end checks again, so dragging in a csv is stopped on the spot.

Figure 12-3 shows the rejection. The block is empty, with a red “Error” marker in the middle and a notice in the top-right corner, Invalid file type: plan.csv. Only .txt allowed. It says “this file type is wrong, only .txt is allowed”, naming both the file and the rule.

Figure 12-3 Wrong type: the front end rejects it on the spot, the value in the block does not move

This check happens in the browser; the server never receives this upload at all. In other words, fileTypes is a rule shown to the user, not a security boundary. Bypass the UI and push a csv straight into the upload endpoint, and the server still accepts it, the handler function still gets the path. One script call to the upload endpoint is enough to prove it. That csv slips quietly into the cache with no notice at all.

Keep this distinction in mind. To build an application that “only handles txt”, writing fileTypes is not enough; the handler function has to judge once more on its own: is the extension right, can the content be read. The former is experience, the latter is correctness, and their costs are far apart. The former is one line of parameters, the latter a few lines of code plus an error message — but only the latter can guarantee that what you get is what you think it is.

The example’s handler function does only the experience half, because it is a demo; in a real product you should at least check the extension before reading the file, and be ready to catch the case of “a binary file with a changed extension” while reading it. An image renamed to .txt passes the extension check, and ReadAllLines throws. What the user should see then is not a stack trace, but a line saying “this file cannot be read”.

fileTypes has two spellings: extensions with a dot ([".txt"]) and category names (["image"], ["text"], ["video"]). Extensions are precise, categories are loose. ["text"] lets in txt, md, csv, and json together, while [".txt"] lets in only txt. The example uses the extension, because this block should accept plain text only; the image-like components in the previous chapter used categories, because what they want is “all images”. Which one you pick depends on whether you mean to express “which files” or “which class of files”.

allowReordering is the third parameter, false by default. Set it to true and a drag handle of two small dots appears on the left of each row in a multiple-files list, letting you drag to swap positions; set it to false or leave it out and the handle does not appear, and the order is whatever order the user picked files in. This switch looks small, but it decides one thing: whether the order is “actively arranged by the user” or “inherited from the sequence in which files were selected”. Turn it on if you want to merge files in the order the user gives; leave it off if order does not matter. A handle you can drag but that does nothing is more confusing than no handle at all.

12.2 File Value Types and Return Structures

type decides what is passed to the handler function. It has two values, which in C# are two completely different things.

Figure 12-4 The two values of type: both routes put the file into the cache first

Write filepath and the handler function receives a string, the path of that file in the cache directory. Write binary and it receives a byte array, with the whole file in memory. The middle cell of Figure 12-4 is shared by both routes. Either way the file first lands in the cache by content hash; the only difference is whether the handler function gets a path or the content.

The example puts the same brief.txt into two blocks and reads each once. The path block shows 387 bytes · 6 lines · first line "Wrapping rules (first draft)", followed by a long cache path; the byte block shows 387 bytes, plus the file’s first four bytes 57 72 61 70. That is the UTF-8 encoding of the character “W”: the first three bytes are the character, the fourth is the start of the next one.

Figure 12-5 The same file, two ways of passing the value; the path block also gives a long path

Figure 12-6 Reading binary: 387 bytes in hand, no path

How to choose? Pick filepath if another program will process this file next (read lines, compute a hash, convert format). You hold only a string, so no matter how large the file it costs no memory; the price is that the file has to keep existing, and once cleaned up there is nothing left to read. Pick binary if you will work on it directly in memory (decompress, encode, slice). It saves opening the file a second time, at the price of memory. A 500 KB file is a 500 KB array inside the handler function.

fileCount and type together decide the signature. The four combinations below are the ones written most often, and the multiple-files cell is the one most often written wrong.

fileCounttypeWhat the handler function receives
singlefilepathstring?
singlebinarybyte[]?
multiplefilepathstring[]?
directoryfilepathstring[]?

Multiple files pass an array to the handler function, not a list. Writing List<string> compiles, but at runtime it reports a very blunt message: what is passed to the handler function is System.String[], which cannot accept the type List<string>. What the component sends is an array, and you have to be able to receive it.

The example does not use the multiple-files-with-binary cell, and in practice it is rare too. Reading several files entirely into memory at once costs the number of files times their size, and multiple-files situations are usually exactly those with many large files. To handle them one by one, filepath with a loop is steadier.

The directory cell deserves its own note. On the server it is the same route as multiple files: both pass an array of paths to the handler function. The difference is entirely on the front end. Multiple files lets you pick several files at once; directory lets you pick only one folder and then collects all the files inside it. So the handler function needs no second set of logic for directories: accepting a string[] covers both sources.

string ReadGroup(string[]? paths) => ReadPaths("Group", paths);

One line. ReadPaths reports one line per file: name, byte count, extension. The directory mode uses the same line, only with the title changed to “Directory”.

All parameters are nullable, because every block can be empty. The empty value is part of the contract. No file means no file, and the handler function has to decide on its own what to say then. The example’s choice is to write “no files yet” into the panel, so that emptiness is visible, rather than let the handler function receive an empty string and guess among a pile of ifs whether it was “not passed” or “passed an empty file”.

The two sources of an empty value need to be kept apart. One is “the user never put anything there”; the other is “they did, but the file is gone now”. The second case also depends on the page. Refresh once and the block is empty, the handler function gets null, the same as never having put anything; without a refresh the block still shows that file name and the value is still there, but the file underneath has already been deleted by the cleanup routine.

The latter is what this chapter really has to guard against, and it cannot be guarded against inside the handler function. Click “Read single” and the handler function is never called at all. Before passing the value to the handler function, the framework first moves this file into the cache; if it cannot, it throws FileNotFoundException, leaves an error in the UI, and the panel stays on its previous line. Figure 12-10 shows exactly that. The block still reads brief.txt, the returned line is still the previous result, with a red “Error” marker added beside it.

So a check like “test whether the file exists before reading” has no place here; it is never your turn to judge. There are only two things you can do: do not treat a cache path as storage; and if you really need to keep a file, copy it into your own directory the moment you get it.

One more thing to know about the binary cell. It reads the whole file into memory, so the larger the file, the more memory the handler function occupies — and that occupancy multiplies by the concurrency count. Ten people uploading 100 MB files at once means 1 GB of arrays on the server. filepath has no such problem: a hundred people uploading at once still means only a hundred strings in memory. That is the first thing to weigh when choosing type: are the files large, are there many users.

One thing to watch in real use of the directory cell. The array passed to the handler function holds every file in the folder, including those in subdirectories and those you did not expect (.DS_Store, Thumbs.db, temporary files left by editors). The example’s ReadPaths reports one line per file, so the user sees those extras; in a real product, either filter them or tell the user plainly that “every file in this folder will be read”.

12.3 UploadButton and DownloadButton

File is “a container”: put files in and watch them line up in a column. UploadButton and DownloadButton are actions: a button, one click, one thing happens.

                upload = gr.UploadButton("Upload button", fileCount: "multiple", fileTypes: [".csv"], type: "filepath");
                download = gr.DownloadButton("Download manifest", value: FileDesk.Write("(no manifest generated yet)"));

The parameter list of UploadButton is the same as the first few of File: fileCount, fileTypes, type. The difference is in the UI. It has no preview area, no file list; clicking opens a picker, and once you choose, it uploads, with the value recorded on the button itself. The example’s upload button accepts csv only, multiple files; Figure 12-7 shows it after a click. The panel reads “Button upload plan.csv”.

Figure 12-7 The upload button: the button itself is the entry point, and the file list is not in the UI

Why have such a thing? Because sometimes what you want is the action “import”, not “this pile of files”. An import button plus one line saying “what was imported last time” is far cleaner than a file list taking up half the screen; once a file is uploaded it should be processed, with no need to keep it sitting in the UI for people to look at.

The upload event of UploadButton is its main entry point, and the handler function receives an array of paths (when fileCount: "multiple"). The example binds it.

    files.Upload.Upload(OnButtonUpload, [files.Upload], [files.Echo], apiName: "Button upload");

DownloadButton is the reverse action: it sends a file to the browser to be saved. Its value is a path, and one click downloads that file. There is one limitation here that the example ran into. value must exist at construction time — a placeholder file will do; a button built empty, whose value a handler function later swaps in, downloads nothing when clicked. So the example first writes a file containing “(no manifest generated yet)” as a placeholder, and swaps in the real one after the manifest is generated.

The reason is not hard to guess. The button has to know “which file it holds” at page load before it can wire up the download route; a button that never had a value has nothing on the front end to wire to, and giving it a value later only changes a field it does not watch. The way around it is simple: give it a placeholder file, or point it at something that really exists from the start. The placeholder’s content gets moved into the cache, so it too gets cleaned up; but after cleanup the button is still in a “wired for download” state, just without that placeholder file. In the example the placeholder really is cleaned up after two minutes, and clicking download then yields an error page. That is exactly what 12.5 covers.

The value of DownloadButton can also be swapped by a handler function; the example’s “Generate manifest” works like the following. The same handler function’s return values are written into both the file block and the button. Both components get the same path and each moves it into the cache once, yet they land in the same directory, because the content is the same and the hash is the same.

The output of File can be downloaded too; the difference is “visibility”. File lays the file out, so the user can see its name, see its size, click the arrow on the row to download, or do nothing at all; DownloadButton has only a button, click or no click. Use File for “the result is here, you can take it”; use DownloadButton for “here is this one file”.

The division of labor among the three components: File handles a visible group of files, UploadButton handles one import action, DownloadButton handles one download. The same file can be written into two of them at once. The example’s manifest appears in both the file block and the download button — two ways of “taking it away”.

12.4 Upload Destination and Size Limits

Where do files land? By default they land in a gradio folder under the system temporary directory, which on Windows is C:\Users\<username>\AppData\Local\Temp\gradio; if the environment variable GRADIO_TEMP_DIR is set, they land in that directory. The example changes it to a folder beside the program itself, so readers can open it and look.

// The four knobs for files: destination, limit, cleanup cadence, and the directories allowed to be served out.
demo.UploadFolder = Path.Combine(AppContext.BaseDirectory, "cache");
demo.MaxFileSize = 512 * 1024;
demo.DeleteCache = new DeleteCacheSettings(TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(120));
demo.AllowedPaths = [FileDesk.Folder];

These four lines sit after gr.Blocks() and before using (demo). They are application-level settings, not component parameters. Where a file lands is the application’s business, not any single block’s.

The structure of the destination is one level deeper than you would expect. Upload a brief.txt and its path in the cache is cache\c519ef57…c97e\brief.txt, one level more than cache\brief.txt. The middle level is the content hash, 64 hexadecimal characters long. Three benefits come from this: the same content uploaded twice takes only one slot; the URL cannot be guessed from the file name; and the question “who does this file belong to” is answered by “is it under this directory”.

Files with different names can live under the same hash directory. When the content is the same but the names differ, both are kept and share one hash directory. Conversely, change one character and upload again: the hash changes, so it is another directory, another file. The cache recognizes by content, not by name.

Recognizing by content has two direct consequences, both worth thinking through before writing an application. First, upload the same file ten times and there is only one copy on disk; the second through tenth uploads take almost no time. What is saved is everything beyond bandwidth. Second, “the path changed” does not mean “the content changed”. Upload the same content again and the path is identical, so the front end cannot tell the difference, and the change event may not even fire. To judge “did the user upload again”, looking at the path is useless; you have to look at something else.

The hash layer has one more layer of salt. Each process generates a random piece at startup and mixes it into the hash, so the same file gets a different path when run today than when run tomorrow. The point of this design is that “an address cannot be computed in advance”. Without the salt, anyone could compute a file’s hash and write out the address before the file even exists. The cost is that after a restart all old paths become invalid, while those files are still in the cache, just with nobody pointing at them anymore. The cleanup routine collects them, so this does not turn into a pile of garbage, but it also shows how short-lived a path is: it does not even survive one restart.

The destination is usually left alone in production. The default temporary directory is managed by the operating system, and cleanup tools know where it is; after changing it to the program directory, a program installed under C:\Program Files may not even have write permission. What needs changing then is the installation method, not this line of configuration. The example changes it to the program directory only so readers can open the folder and see those hash directories with their own eyes.

MaxFileSize is the second knob, in bytes. The example writes 512 * 1024, that is, 512 KB. What happens when it is exceeded? Two gates, first loose then tight.

The first is on the front end. Figure 12-8 shows a 542 KB large.txt pushed in. The block is empty, with a red “Error” marker in the middle and a notice in the top-right corner, File(s) exceed the maximum allowed size of 512.0 Kb: "large.txt", with both the limit and the file name in it.

Figure 12-8 Over the limit: the block is empty, and the notice states the limit and the file name

The second is on the server. When the front end cannot stop it (say a script posting straight to the upload endpoint), the server measures as it reads, stops on the spot once over the limit, and returns 413 with File size exceeded maximum allowed size of 524288 bytes. The number in that line is a byte count, not KB: 512 times 1024 is 524288. Both routes have to block, because the front-end one blocks mistakes, while the server one protects the disk.

When “measuring as it reads”, an oversized file is not first fully written to disk and then deleted; writing stops at the limit, so the disk it occupies is at most the limit. Writing null (that is, leaving this parameter unset) means no limit, and anyone can fill the disk with a 10 GB file. That is something a reverse proxy or your own middleware should handle, not something to expect from the component.

12.5 Cache Cleanup and Allowed Paths

The third knob is DeleteCache, with two time parameters: how often to check, and how old a file must be before it is deleted. The example checks every 20 seconds and deletes files older than two minutes. That cadence is deliberately turned up; a normal application would not set it this way.

Leave this parameter unset and nothing in the cache is ever deleted; everything stays until you clear it yourself. Once set, the application periodically sweeps the files it wrote itself and deletes those past their age; when the application stops, the ones it remembers are deleted along with it. Note the qualifier “it wrote itself”: cleanup only touches files the application has recorded, and will not delete things others placed in the same directory.

The two times each govern one thing; do not mix them. The first is “how often to look”, which decides the delay before deletion. With 20 seconds, a file is deleted at the latest 20 seconds after it expires, 10 seconds on average. The second is “how old counts as old”, measured from the file’s last write time, not from its upload time. (20, 120) means: look every 20 seconds, and delete anything untouched for over two minutes. So the moment a file truly disappears falls between 120 and 140 seconds, not at one precise instant. Keep this in mind when writing docs about “how long until a file expires”: do not present a planned value as a promised one.

Why is age measured from “last write” rather than “creation”? Because the cache stores by content. The same content may be shared by many operations, and one new reference amounts to writing it once more. Measured from last write, a file in use is not deleted; measured from creation, a template file used for three days would vanish on the third day. This choice has no effect on a flow that “uploads one file and uses it right away”, but a large effect on a flow that “keeps a long-lived asset in the cache”. So long-lived things do not belong in the cache.

Writing null (leaving this parameter unset) turns cleanup off, and the cache only grows; that is convenient in development (files survive a restart), but in production it will fill the disk sooner or later. To leave an opening for “cleanup managed by someone else”, do not set it, and instead bring the directory under the system’s temporary-file cleanup policy. That policy does not know “which files the application is using”, so do not expect it to be precise.

Both cache screenshots upload the same brief.txt into the single-file block, one right after uploading, one two and a half minutes later. Check the cache immediately after the upload: 15 files, 279,575 bytes, with brief.txt the most recently written; click “Read single” on that same value and it reports 387 bytes, 6 lines. Check again two and a half minutes later: 11 files, 278,691 bytes, and the most recently written is something else; the block still reads brief.txt, and clicking “Read single” again leaves the returned line unchanged, with a red “Error” marker added beside it.

Figure 12-9 Checked right after upload: fifteen files in the cache, the newest one just uploaded

Figure 12-10 Two and a half minutes later: the file is cleaned up, the block still shows the name, and reading again errors

A cache path is a promise that “it is here right now”. Write it into a database, into a config file, send it to someone else, and a while later it is a dead link. To keep a file, you have to copy it into your own directory inside the handler function. The example’s out directory is used exactly this way: the generated manifest is written there first, then moved into the cache by the component.

The copy moved into the cache is cleaned up too. In the round of Figure 12-10 the cache drops from 15 files to 11; of the four that disappeared, only one was just uploaded, and the other three were temporary files left by other modules. The cache treats everything that lands in it the same.

The fourth knob is AllowedPaths, which answers a different question: besides the cache directory, which other directories may the file endpoint serve. By default, none at all. The application serves only files it wrote itself, and gives out nothing from anywhere else.

The example adds the assets directory, so the UI gains a link “Original asset brief.txt” pointing at /gradio_api/file=<path>. Clicking it opens that file, because it is in an allowed directory. Remove that line and the same link returns 403, with a body of File not allowed: ... plus that path.

The cost of this switch needs to be stated plainly. Allowing a directory means letting anyone who can reach this application read every file in that directory. Allowing C:\Users\you\Documents puts the whole Documents folder on the web. If you allow anything, allow a dedicated directory holding only files meant for outsiders; do not allow a home directory, do not allow the program directory.

12.6 Import, Upload, and Clear Return Values

File has five events: change, upload, clear, delete, download. The names are easy enough, but which ones actually fire and what they bring back when they do has to be tried one by one.

The example binds three: upload, change, and delete, on the single-file block, the group-of-files block, and the upload button respectively.

    files.One.Upload(OnUpload, [files.One], [files.Echo], apiName: "Single upload");
    files.One.Change(OnFileChange, [files.One], [files.Echo], apiName: "Single change");
    files.Group.Upload(OnGroupUpload, [files.Group], [files.Echo], apiName: "Group upload");
    files.Group.Delete(OnGroupDelete, [files.Group], [files.Echo], apiName: "Delete one");
    files.Upload.Upload(OnButtonUpload, [files.Upload], [files.Echo], apiName: "Button upload");

A single upload fires two events, upload and change. The former means “the file landed”, the latter “the value changed”; by outcome they are the same thing, by semantics two different angles. Bind upload if you only care that “a new file came in”; bind change if you care “what this value is now”. Binding both logs twice, which is what the example’s single-file block does, so two lines appear in a row on the panel.

Delete one entry from a multiple-files list and what fires are delete and change. delete brings back the array as it stands after the deletion. When the example deletes down to one file, the panel writes “Delete one, 1 left”. That number is what remains, not what was deleted; do not read it backwards.

Click the clear button in the component’s top-right corner and only change fires, bringing back an empty value; the panel writes “Change: value cleared”. The clear signal exists, but this action does not fire it.

Click the download arrow on the right of a file row and the browser saves the file directly; the download event does not fire, so the example does not bind it.

These two are the actual behavior. So the component will not tell you “what the user downloaded”; to log it, place your own button that records a line first and then fetches the file. Likewise, to log “the user cleared it”, bind change and treat an empty value as a clear.

Lay these out in a table and you will not have to flip back to check while using them.

EventWhen it firesWhat it brings back
uploadA file landsThe new path or array
changeThe value changed (upload, delete, and clear all count)The current value; empty after clearing
deleteOne entry deleted from a multiple-files listThe array after deletion
clearNot fired by clicking the clear button—
downloadNot fired by clicking the download link—

The most useful row in this table is change. It fires most often and carries the most useful information: what the value is now. Bind just change if you want “log a line whenever the user touches this block”; only when you want “the user added one” and “the user deleted one” handled separately do you need upload and delete.

That delete brings back the array after deletion is critical when designing the handler function. It does not tell you which entry was deleted. To get that, you have to compare this array with the previous one. The example does not store the previous value, so the panel only writes “how many are left”. To be precise down to “notes.md was deleted”, you have to bring in state, which is a matter for Chapter 14.

UploadButton has fewer events: upload, change, click. upload is the main one, firing once when a selection finishes, bringing back an array of paths. click is still useful when “the same file was selected”: the value has not changed, so upload may not fire, but the user did click.

The handler function signature for an event follows its component. A single file takes string?, multiple files and buttons take string[]?. Get it wrong and it does not fail silently; it throws a type-conversion error, the same one as in 12.2.

12.7 Output Files and Download

The inbound route is done; the outbound one has to answer “where is the file” too.

The handler function returns a path, and the component does one thing after catching it. If that path is not in the cache directory, it copies the file into the cache and sends the address of the cached copy to the front end. So after returning out\sheet.txt, the address of that file in the UI is cache\<hash>\sheet.txt, not out\sheet.txt.

(string, object, object) MakeSheet(string[]? paths)
{
    var sources = paths ?? [];

    if (sources.Length == 0)
    {
        return ("**Manifest** no usable files: load a group first, or drag a few files into the group.", gr.Skip(), gr.Skip());
    }

    var path = FileDesk.Write(FileDesk.Sheet(sources));

    return ($"""
        **Manifest** {FileDesk.Describe(path)}

        Written to `{path}`; after it returns, the component moves it into the cache.
        """, path, path);
}

Three return values: one line for the panel, the manifest file block’s value, and the download button’s value. The last two are the same path. Writing the same path into two components moves it into the cache once for each, but the content is the same and the hash is the same, so they still land in the same directory.

The FileDesk.Write layer does not reference Gradio.NET.

    public static string Write(string text)
    {
        Directory.CreateDirectory(OutputFolder);

        var path = Path.Combine(OutputFolder, "sheet.txt");
        File.WriteAllText(path, text + "\n");

        return path;
    }

It only writes the text into a file and returns the path. Whether the file should be moved into the cache, and where, is the component’s business. The business code does not know the cache exists, so it does not need to change for it.

Figure 12-11 shows it after generation: sheet.txt appears in the manifest file block, 215 bytes, with a download arrow on the right; the download button gets the same value too.

Figure 12-11 Generating the manifest: the file block and the download button both get the same file

Click the download button and the browser saves a 215-byte sheet.txt. This file is byte-for-byte identical to the one in the out directory. The manifest has only four lines (one for each of the three files and a “Total” line at the end), and 215 bytes is the length those characters occupy in UTF-8, not the sum of the three files’ byte counts. The number 1,078 is in the manifest body; it is what the “Total” line writes.

Can the downloaded thing be used again? Yes. Figure 12-12 shows the result of uploading that just-downloaded file back into the single-file block and clicking “Read single”: sheet.txt, 215 bytes, 5 lines, with the first line being the manifest’s first entry.

Figure 12-12 Read again after download: the byte count matches, and so does the content

The download-then-read round trip is worth walking through once. What it confirms is that outbound and inbound files land on disk under the same rules. Writing out lands by content hash, uploading back lands by content hash again, and both times it is the same content, so the byte counts match. There is no encoding conversion in between, no newline normalization, no BOM added or removed.

This round trip brings out one more consequence. If the outbound file is cleaned up in the cache, clicking download again only yields an error page. To let someone still download it two minutes later, copy it into your own directory before then, or turn cleanup off.

12.8 Chapter Summary

The three parameters fileCount, fileTypes, and type decide the contract. fileCount has three modes: single file passes string, multiple files pass string[], and directory also passes string[] (the same route on the server, the difference is in the front-end picker); it also changes the UI along the way. Single file has no delete button; multiple files have handles, byte counts, download, and delete on each row. fileTypes is written into the browser’s picker and rechecked on the front end, stopping anything non-compliant on the spot with a notice, but the server does not recheck, so it governs experience, not correctness. type has two routes: filepath passes a path, binary passes bytes; for the same 438-byte file, the values the two routes pass to the handler function are completely different.

UploadButton and DownloadButton are actions, not containers. The former is one import per click, with the value recorded on the button, and the upload event brings back an array of paths; the latter sends the file its value points at to the browser on a click, and value must exist at construction time — a button built empty cannot be clicked even if a handler function swaps its value in later.

All four knobs are application-level. UploadFolder decides where files land (by default a gradio folder under the system temporary directory, which can be changed to one beside the program), MaxFileSize decides how large they can be (a front-end notice and a server-side 413, two gates), DeleteCache decides how often to clean up (unset means no cleaning), and AllowedPaths decides which other directories the file endpoint may serve (by default only the cache, everything else is 403).

A file lands at <cache directory>\<content hash>\<original file name>. Splitting directories by content hash has the benefits that the same content takes only one slot, addresses cannot be guessed, and “is this the file from this upload” is judged by the directory. The cost is that the path itself means nothing and cannot be used as storage. A file uploaded two minutes ago may already be gone two minutes later, and the value in the block goes empty along with it.

As for events, upload and change both fire on upload, delete fires when one entry is deleted and brings back the array after deletion, and neither clear nor download fires. Clearing fires only change, downloading fires nothing. To keep a log, bind change as the catch-all.

The outbound route is symmetric with the inbound one. The handler function returns a path outside the cache, the component moves it into the cache, then sends the cache address to the front end; the downloaded bytes are identical to the ones written out, and uploading them back to read gives matching byte and line counts.

Up to this chapter the workbench can handle text, tables, charts, audio and video, and files, and can return results to the UI. But every block on the page is “one-shot”. Change the topic and you have to clear it; nothing from the previous round carries over. The next chapter switches to conversation. Messages accumulate, round after round, and the UI has to remember what was said before.

Chapter 13. Chat Components

The previous ten blocks were all “one question, one answer” UIs: fill in a few inputs, click a button, look at one result. A chat is not like that. It accumulates, one message after another, and users act on what has already been said — they like it, retry it, undo it, or edit a line and say it again.

One value holds the whole history, not the single numbers or files from earlier chapters; the UI also has a set of buttons that the component generates itself.

The sample adds an eleventh block to the workbench. The chat module: a starting conversation of four messages, an input box, an input with an attachment, and a script for two speakers. Replies are hardcoded: this chapter does not call a model service.

First, draw a boundary. This chapter is about “how to use the chat as a UI”, not “how to hook up a large model”. The line between the two is clear. Replace the line in the handler function that builds a string with one HTTP request, and the chat is connected to a model. No UI code has to change in between. The other way round, if the UI is set up wrong, connecting a model only gives you a box you can talk to. So get the UI right first.

13.1 Chatbot Message Structure

The value of Chatbot is a list of ChatMessage. One message has four fields.

Figure 13-1 The four fields of one message, and the history as an array of those messages

role is who is speaking, and there are only three: user, assistant, and system. Write a fourth and it throws; the front end aligns messages by role. content is an array, not a string; this is the structural basis of the chapter, expanded in 13.2. metadata and options can be absent.

This is what the four fields look like when sent to the front end.

{"role": "user", "metadata": null, "content": [{"text": "Explain the file module from Chapter 12.", "type": "text"}], "options": null}

This JSON explains several things that come later. content is an array, so one message can hold several things; each block has a type, and the front end picks a renderer by it; metadata and options are there even when empty, so code reading this JSON never has to write “this field might not exist”. When you build JSON by hand to call the API, build it in this structure.

Figure 13-2 shows the sample’s four messages. The first two are a question and an answer; a small collapsible “thought” floats above the second assistant message; the third is a follow-up question; the fourth has a file card hanging below the answer.

Figure 13-2 Four messages: bubbles, a collapsed thought, a file block, and a toolbar under each message

Where does the history live? In the component’s value. The sample does not use state (that is Chapter 14’s business); instead it has the handler function receive the whole list and return the whole list.

(IReadOnlyList<ChatMessage>, string, string) Send(IReadOnlyList<ChatMessage> history, string text)
{
    var next = (history ?? []).ToList();

    if (string.IsNullOrWhiteSpace(text))
    {
        return (next, text, "**Send** the input is empty, nothing was sent.");
    }

    next.Add(new ChatMessage(text.Trim(), ChatRole.User));
    next.Add(new ChatMessage(ChatDesk.Reply(text, next.Count), ChatRole.Assistant));

    return (next, "", $"**Send** now {Summary(next)}");
}

The sample also binds Submit to the input box, so Enter and clicking Send go to the same handler function. Without that binding, Enter does nothing and the user has to reach for the button. And pressing Enter to send in a chat box is muscle memory; without feedback people assume it has frozen.

Three return values: the new conversation, the cleared input box, and one line in the panel. Where does Chatbot’s value come from? The front end sends the current conversation along with the request. It always remembers which messages it is showing. So “multiple turns” needs no extra storage. The user sends a line, the front end sends it together with the history, and the handler function appends two messages at the end and writes them back to Chatbot.

The order is guaranteed by this way of writing too. The sample adds the user’s line first, then the answer, so the array is always “question, answer, question, answer”; add them the other way round and the UI shows “answer first, question after”. In a multi-turn chat, “is the order right” is a matter of array indexes. Undo, retry, and edit all work by index; get the order wrong and all of them land in the wrong place.

The second return value is an empty string, and you cannot leave it out. After sending, the input box has to be cleared, or the user sees the line they just typed still sitting there and assumes it was not sent. The sample’s empty-input branch hands the original text back (return (next, text, ...)) on purpose. When nothing was sent, do not wipe out what the user typed.

This approach has a cost, and 13.8 spells it out. The history travels with every request, and one page refresh wipes it. To keep it across refreshes you need state; to keep it on the server you have to store it yourself. This chapter is about understanding the value you already have in hand.

One note about the system role. It is neither “user” nor “assistant”; it usually holds an opening instruction, who this assistant is and what rules it speaks by. The front end draws it as a centered or marked notice, and it does not take part in the question-and-answer alignment.

Once the handler function has the history, besides appending to it, it commonly does two more things: read it and trim it. Reading is for context — what the last line asked, which words came up earlier. Trimming is because the history keeps growing until one request can no longer hold it. Trimming usually keeps the most recent rounds, or keeps by word count. The sample does not trim, because four messages are far from the limit; when you really connect a model, “how many rounds of history to carry over” is a number you have to decide yourself.

Every entry in history is a ChatMessage. The Text property is all of its text blocks joined together; Content is those blocks themselves. Code that only cares about “what was said” reads Text; code that has to handle files or components reads Content. Both are there, and which one you pick depends on whether you need anything beyond the blocks.

13.2 Content Blocks and Message Metadata

content is an array because a message can hold more than one piece of text. Three kinds of block.

  • ChatContent.TextBlock(text), a piece of text, the most common;
  • ChatContent.FileBlock(file, alt). A file; the front end draws it as an image, audio, or a file card according to its type;
  • ChatContent.ComponentBlock(...). A component; the front end draws it with that component’s own renderer.

The last message in Figure 13-2 is exactly “a piece of text + a file”: the text gives the conclusion, the file card carries the attachment. The file card shows the file name and extension, clicking it downloads, and allowFileDownloads is on by default.

The sample puts these two kinds of block together.

// The content of one message is an array of blocks: a piece of text, plus (optionally) a file.
static IReadOnlyList<ChatContent> Blocks(Turn turn)
{
    var blocks = new List<ChatContent> { ChatContent.TextBlock(turn.Text) };

    if (turn.Attachment is { } name)
    {
        blocks.Add(ChatContent.FileBlock(
            new FileData { Path = Path.Combine(AppContext.BaseDirectory, "assets", name), OrigName = name },
            "Attachment"));
    }

    return blocks;
}

FileData is the file object from Chapter 12: path, name, size, type. Once the component has it, it moves the file into the cache just like a file block, and the front end fetches it from the file endpoint. So what Chapter 12 said about “paths go stale” holds here too.

What a file block is drawn as is decided by the file’s type. Images become thumbnails, audio becomes a playback bar, video becomes a player, and everything else becomes a card with a name and extension. The txt file in Figure 13-2 is the last kind. That decision is made on the front end; the server only sends the file address, so “whether it can be displayed” depends on the file itself, not on which parameters you wrote.

The third kind of block (component) is used less often but is powerful. Put a table or a chart in a message and the front end draws it with that component. It needs four things: the component’s name (the spelling used in configuration, for example "dataframe"), the value it carries, the parameters used to construct it, and its properties. The last two travel with the message, because the front end uses them to rebuild the component. Give only the value and no properties and you get the component in its default shape. The sample does not use it, because there is no reason yet to put a table into a chat.

metadata decides what a message “looks like”. It governs a few things meant for the UI, not labels for a machine to read.

  • Title. Give the message a title and it becomes a collapsible block. The “Thought for 3 seconds” in Figure 13-2 is one;
  • Log and Duration. Extra notes shown beside the title; the sample writes “Looked through two screenshots from Chapter 12” and 3.2 seconds;
  • Id and ParentId. Let one message hang under another for multi-level thinking. A child message’s ParentId is the parent’s Id, and the front end indents it one level;
  • Status. Pending makes the front end spin and expand; Done collapses.

The sample gives the second assistant message the first three.

        new("assistant", "First see where it lands, then when it disappears.", "Thought for 3 seconds", "Looked through two screenshots from Chapter 12", 3.2),

This line is business data in core; the UI turns it into MessageMetadata. The value of that collapse is that “the process beyond the answer” can be folded away on its own. The user sees the conclusion first, and opens it only if they want to know why.

Whether to use metadata depends on whether the message needs “layers”. A one-line conclusion does not; a process of “what was checked first, how long the thinking took, and what came out at the end” does. Fold the process away and the main text holds only the conclusion, which makes the chat cleaner to read. The other way round, if every message carries a title, the user has to click once more every time to see the answer, which turns a convenience into an obstacle. The sample gives only the second of its four messages a thought; that is the sense of proportion.

Status deserves its own note. Write Pending and the front end spins on that message and expands it; write Done and it collapses. This is not decoration. With streaming output you first put down a Pending assistant message, fill it in piece by piece, and finally change it to Done; what the user sees is “thinking” rather than “stuck”. That is Chapter 16’s subject; here you only need to know the field exists, and that it governs “process”, not “content”.

options is the fourth thing. A message can carry a few clickable options, so the user clicks one instead of typing. It takes a series of ChatOption, each with a value and display text; when one is picked the app receives that value. When should you use it? When the answer is not unique but there are few choices — “Expand further?” with “Yes” and “No” is less work than making the user type two words. The sample does not use it: in a chat with only fixed replies, options would have nothing to reply with.

13.3 Layout, Height, and Rendering Options

layout has only two values, and you can see the difference at a glance. bubble splits the two sides left and right, each a rounded bubble; panel puts both sides into full rows, left-aligned, more like a record.

Figure 13-3 On the left, panel layout; on the right, Markdown rendering turned off

The right-hand panel in Figure 13-3 has one more switch, renderMarkdown: false. With the same line “Cleanup checks every 20 seconds, right?”, rendering on gives bold and monospace; off shows the asterisks and backticks as they are. When should you turn it off? When the message content is itself “source text meant to be seen”. A chat that teaches Markdown, a chat that pastes logs. It is on by default.

height is the block’s height: write a number and it is pixels, write a string and it is a CSS length. It decides “how many messages you see at once”. The sample writes 480, which fits four messages exactly; after ten rounds you have to scroll. There is no standard answer for how tall to make it, but there is a rule of thumb: keep “the last two rounds” fully visible. One round is a little over a hundred pixels (one message each for question and answer), so two rounds are around 300; taller wastes the page, shorter makes the user scroll back every time.

placeholder is the line shown in the middle when the chat is empty; there is none by default. Its position overlaps with examples (both appear only when the chat is empty), so you generally pick one. Either give a hint (“Ask something to start”), or give a few clickable examples. Give both and the examples push the hint upward.

autoscroll decides whether a new message scrolls to the bottom. The sample turns it on. After sending a line, your eyes follow to the newest one. Turn it off and, in a long chat, the user stays put after sending and has to scroll down themselves. That is actually right for a “log stream” style UI.

resizable, minHeight, and maxHeight are a group. The first lets the user drag the block’s bottom edge to change the height; the other two give it lower and upper bounds. Write none of the three and the block’s height is fixed by height. If you write resizable: true, write minHeight along with it. Otherwise a user can drag the chat down to a slit and then cannot find a bottom edge to drag it back. maxHeight governs “how tall it can get at most”, used together with height. height is the initial height, maxHeight is where it stops growing.

There is one more inconspicuous parameter that bites: groupConsecutiveMessages, true by default. Two adjacent messages of the same role are merged into one bubble. Usually that is a good thing — when the model says two segments in a row, they look like one. But once you delete the user message in between, two assistant messages sit together and merge into one (the undo in 13.4 runs into this). To tell them apart one by one, write false.

examples appear only when the chat is empty. The sample gives the main chat two, and they surface only after you click “Clear chat” (in a chat with content, like Figure 13-2, they take up no space). Clicking one fires example_select and brings back Index (which one) and Value (the example itself, a dictionary with a text key). But it does not fill the example into the chat by itself — you have to write that step.

This one is easy to trip over. In ChatInterface, clicking an example means “send this question straight away”, because it does the sending for you; with a handwritten Chatbot, the example buttons only tell you “which one the user clicked”, and turning the example into a question and an answer is still your job. The sample’s handler function therefore has two extra lines. It treats the example’s text as one user message, pairs it with an answer, and puts both back into the chat. Without those two lines, clicking an example does nothing: the button stays, the chat stays empty.

An example can also carry an icon and files. Besides Text, ChatExample has DisplayText (what to show), Icon (the small image beside it), and Files (attachments the example brings). You use these for prompts like “Upload an image and try”.

13.4 Feedback, Retry, and Undo

Chatbot has ten events; this section covers four of them: like, retry, undo, and edit. They are all triggered by buttons the component brings with it, in that row of small icons under each message.

These buttons live under each message, not in a toolbar at the top of the page. The position is the design. Like, retry, and undo all target “this one”, so put them beside it and the user does not have to select first and then say “yes, that one”. The cost is one more row of icons per message, and a long chat starts to look dense. If that feels noisy, buttons can drop the copy ones and editable set to null removes the pencil, but retry and undo cannot be dropped — they are part of this round of the conversation.

First, a counterintuitive one: if you don’t bind like, there are no thumbs-up and thumbs-down. In that row of icons under a message, copy, retry, and undo are all there, and only the two thumbs are missing; they appear once you bind it (the lit thumb in Figure 13-4). The component is waiting for someone who can catch the rating.

Figure 13-4 A like: message 1 is liked, and the callback carries the position and that message’s text

like brings back three things. Index is which message, Liked is “like or dislike” (a Boolean with the default two options, the value of the chosen option with custom ones), and Value is that message’s text. The sample joins them into one line.

string OnChatLike(LikeData data)
{
    var said = data.Value switch
    {
        object[] blocks => string.Join(" ", blocks.Select(block => block?.ToString())),
        null => "",
        _ => data.Value.ToString(),
    };

    return data.Liked is true
        ? $"**Like** message {data.Index}: \"{said}\""
        : $"**Dislike** message {data.Index}: \"{said}\"";
}

The type of Value is object, but what you actually get is an array of strings, one entry per text block in that message. So handle it as an array here; writing data.Value is string will never be true.

What do you do after getting the rating? The sample skips this step, because it needs to “remember”: which messages were liked, and by whom. Without state, a rating can only be written to a log, sent to an external service, or shown once as the sample does. To really “remember which one was liked last time”, you store the rating in state (Chapter 14) and then write it into the component through feedbackValue at render time, so the thumb stays lit.

feedbackOptions decides how many options there are and what they are called. Two by default (like, dislike); write custom strings and you get custom buttons; more than two options are folded into a menu. Whatever value you write is what Liked brings back. So “like/dislike” is a Boolean check, while “Accurate / Inaccurate / Off-topic” has to be checked by value.

retry is “answer this one again”. Its button appears only in the last round, because “answer again” means “a different answer to that last question”. It brings back Indices (which messages this retry covers), Index (the first of them), and Value (that question’s text).

The sample’s retry only rephrases; it does not call a model.

(IReadOnlyList<ChatMessage>, string) OnChatRetry(IReadOnlyList<ChatMessage> history, RetryData data)
{
    var next = (history ?? []).ToList();
    var at = data.Indices.LastOrDefault();

    if (at < 0 || at >= next.Count)
    {
        return (next, "**Retry** that message was not found.");
    }

    Answer(next, at);

    return (next, $"**Retry** the answer after message {at} was replaced.");
}

Answer is that small function in the sample. It replaces the answer after message at, and inserts one if there is no assistant message after it. Editing uses the same one. “Replacing the answer to a question” is the same job in retry and in edit.

Figure 13-5 shows it after the click: the last answer is replaced with a different phrasing (the sample picks one at random), and the first three rounds are untouched. Random.Shared is the sample simulating “asking again gives a different answer”; with a real model, that line becomes one request.

Indices is an array rather than a single number because one retry can cover the two messages of “a question and an answer”. The sample uses only the last position (answer the last question again, replace its answer), which is also the most common use. If you want “start from this question and redo everything after it”, truncate at the first item of Indices and generate again from there.

The retry button appears only in the last round, and that cannot be changed: the component decides it, it is not a parameter. To “re-answer a round in the middle”, you have to make your own button and send that question again.

Figure 13-5 Retry: only the last answer is replaced, the history is unchanged

undo is “take this round back”. It brings back Indices and Index. It gives only the position of the user’s message; the assistant’s is not included. So undo has to delete two messages itself.

(IReadOnlyList<ChatMessage>, string) OnChatUndo(IReadOnlyList<ChatMessage> history, UndoData data)
{
    var next = (history ?? []).ToList();
    var at = data.Indices.LastOrDefault();

    if (at < 0 || at >= next.Count)
    {
        return (next, "**Undo** that round was not found.");
    }

    next.RemoveAt(at);

    if (at < next.Count && next[at].Role == ChatRole.Assistant)
    {
        next.RemoveAt(at);
    }

    return (next, $"**Undo** removed one question and one answer, now {Summary(next)}");
}

What happens if you delete only the user’s message? The two remaining assistant messages sit together, groupConsecutiveMessages merges them into one bubble, and the answer looks longer — that is the wrong deletion. This is where mistakes happen. Undo is “a question and an answer”, not “one message”.

One more thing to be clear about. What the UI looks like after undo is decided by the array you return; the component does not touch it again. So “how many to delete” is entirely up to you. Delete a pair, delete a pair and add an apology, or delete nothing and just make a note — all are fine. The component only tells you that the user clicked undo.

Figure 13-6 Undo: four messages become two, and the callback reads “now 2 messages: 1 user, 1 assistant”

edit requires editable to be on first. Write "user" and every user message gets a pencil; write "all" and the assistant’s can be edited too; write null (the default) and there are none. Click the pencil, the message becomes an input box, and after editing you click its own “Send”; the edit event brings back Indices, PreviousValue (before the change), and Value (after the change).

On receiving it, the sample rewrites that question’s answer. This is the most common use of editing. If the user changed what they asked, the answer should not still be the old one.

The handler functions of the three events can all return a new conversation — that is what they are really for. They can also return just one line and leave the conversation alone; that becomes “make a note”, the kind in Figure 13-4.

Editing has one consequence that is easy to overlook. After the change, the original answer no longer stands. The sample rewrites the answer along with it; change only the user’s line and leave the answer, and the UI shows “asks A, answers B”. So an edit handler usually looks just like retry: replace that question, then generate a new answer.

Use editable: "all" with care. It lets the assistant’s message be edited too, so the user can change the model’s answer into anything. If the chat is going to be exported and treated as a record, you can no longer tell who said what in edited content. The case for open editing is usually “make the question clearer”, and "user" covers that.

All four events go through the queue, like an ordinary button: click first queues, then executes. So click retry twice quickly and both run, with the later one overwriting the earlier result. To prevent that, use triggerMode from Chapter 15.

13.5 What ChatInterface Saves You

Across the four sections above you wrote the chat block, the input box, the send button, the send handler function, four event handler functions, plus clearing and examples. ChatInterface packs that whole set into one function.

// ChatInterface builds an app of its own: the whole page is one chat and it cannot be placed inside another layout.
var demo = gr.ChatInterface(
    Reply,
    title: "Chat-only app",
    description: "One function, one input box, one chat; it builds everything else for you.",
    examples: new[] { "What does Chapter 12 cover", "Where do the files land" });

demo.Launch(serverPort: 7862);

// The message and the history are both handed over by the framework: you do not append them yourself, and you do not clear the input box yourself.
static string Reply(string message, IReadOnlyList<ChatMessage> history)
    => $"Round {history.Count / 2 + 1}: you asked \"{message}\".";

Figure 13-7 shows it running: a title, a description, one chat, and an input box at the bottom. The handler function has only two inputs (this line and the history), returns only one line, and takes care of nothing else.

Figure 13-7 One function buys a whole chat page: title, description, chat, input box

The things it does for you can be counted one by one: the input box and its Enter-to-send, the send button and the stop button, appending the user’s line to the history, passing the history to the handler function, appending the answer, clearing the input box, wiring retry and undo, editing and regeneration, the examples bar, and caching the answers for the examples. In the handwritten version, every one of those has to be wired up by hand.

Its sending also happens to solve a failure case. When the handler function throws, the user’s line should still be in the chat and the input box should be empty, rather than both kept or both lost. ChatInterface gets that order right. You can get it right by hand too, but you have to think first about “what the UI should look like on failure”.

Its toolbar comes built in as well. The chat block has three icons in the top-right corner (share, copy the conversation, copy all) and a clear button beside them; under each message are copy and (only when bound) retry, undo, and like/dislike. To change that top-right row, the buttons parameter can subtract but not add. It takes names, not components.

It has a few more parameters worth knowing. multimodal: true swaps the input box for MultimodalTextbox, and the handler function takes MultimodalText instead of a string. additionalInputs adds a collapsible block of extra inputs below the chat (for example a “Tone” dropdown), and the handler function receives those values after the history and the message. additionalOutputs lets the handler function’s result fill a few more components, such as a companion image.

But there are two things it does not give you.

The first is layout. gr.ChatInterface returns a Blocks. It builds an app of its own. You cannot tuck it into one column of the workbench. It does not recognize an outside layout, and you cannot drop it in as a component. So choose it only when “the whole app is one chat”; if you already have a workbench, you have to handwrite Chatbot.

The second is detail. Its chat block, input box, and buttons are all in their default shape; you can only fine-tune them with parameters (chatbot and textbox can be swapped for ones you build yourself), you cannot change the structure. Like and dislike are off by default. flaggingMode defaults to never; to turn it on you write "manual". That is why the assistant message in Figure 13-7 has only copy, retry, and undo beneath it, and no thumbs.

There is one less obvious thing it withholds: it gives you only one chat. If you want two chats side by side on a page (say “Ask the docs” and “Ask the code”), ChatInterface cannot do it. The app it builds has exactly one chat block. Here too you have to handwrite it.

The choice starts with this question: first ask “does this app have anything besides the chat?”. No — use ChatInterface, done in twenty lines. Yes — handwrite Chatbot and treat the chat as one block in the workbench. There is a middle case too: only one chat, but you want to change the structure (a custom toolbar, a live result panel beside the chat). Start from Chatbot there as well, because ChatInterface does not expose its structure.

The sample gives you both. samples-en/chapter13 is the handwritten version (inside the workbench shell), and samples-en/chapter13/interface is the twenty lines of ChatInterface. Launching both and comparing them is faster than reading two pages of explanation.

The difference in code size is an order of magnitude. The handwritten version: one chat block, an input box and a button, seven handler functions (send, like/dislike, retry, undo, edit, examples, read attachment), plus ten lines of bindings to wire them together. The ChatInterface version: one gr.ChatInterface call and one handler function. The former gives you control (what each block looks like, what each button does when clicked, how the UI changes on failure; the latter gives you speed) — twenty minutes and you have a working chat.

Which one to pick is not a question of “more advanced or less”. Use the handwritten version for an app that is only a chat, and every extra line repeats work the framework already got right; a workbench that already has ten blocks has no room for ChatInterface, which builds an app of its own.

13.6 Text and Attachments in MultimodalTextbox

Sending an image or a file in a chat uses MultimodalTextbox. The name says it all: one input box that you can both type into and attach files to.

Its value is MultimodalText: a Text and a Files. The sample reads it out.

string ReadMultimodal(MultimodalText? value)
{
    if (value is null)
    {
        return "**Attachment** no value.";
    }

    var files = value.Files?.Count ?? 0;
    var names = files == 0 ? "" : string.Join(" / ", value.Files!.Select(file => Path.GetFileName(file.Path)));

    return $"""
        **Attachment** Text "{value.Text}", {files} files

        {names}
        """;
}

Figure 13-8 shows it with an image attached and a line typed: the input box holds the thumbnail and the text, and after clicking “Read attachment” the panel shows the text, the file count, and the file names.

Figure 13-8 An input with an attachment: text and files travel to the server together with the request

The three parameters are the same set as File. sources governs the entry points (upload, microphone, camera), fileTypes which types are accepted, and fileCount how many. The sample enables only upload and accepts only images, so opening the attachment button shows just a file picker.

Attached files land in the cache just like uploaded ones, and each item in Files carries a path, a name, and a size. So Chapter 12’s rule “don’t treat the path as storage” still applies. If the handler function needs this image, use it now or copy it away yourself.

There is no automatic relationship between it and Chatbot. The sample treats it as a standalone block: fill it in, click “Read attachment”, read the value. In a real chat you usually use it as ChatInterface’s input box (multimodal: true, with a handler function taking MultimodalText), or wire its value to a send button yourself.

When you wire it yourself, that step is the same pattern as the send in 13.1, with one extra job: turn the attachments into file blocks in the message. Text goes into a text block, each file into a file block, together they form one user message, and then you append an answer. The sample does not wire this up (its send button is paired with an ordinary input box), but the way to assemble it is the Blocks function from 13.2: one block for the text, one for the file.

The difference between MultimodalTextbox and Textbox is more than “one extra attachment button”. It has no type (no password box, no email box), lines and maxLines decide how tall the input box grows, and maxPlainTextLength limits the length of the plain-text part. It also draws attachments as thumbnails lined up inside the input box. The small image on the left of Figure 13-8 is one: the user can see what they attached and can click it away.

How many attachments one message can carry is decided by fileCount. Write "single" and you can attach only one; "multiple" allows several, and each one attached becomes a separate file block in the message. Figure 13-8 has only one image, so it reads out as “1 file”; attach three and you get three file blocks in a row, each with its own thumbnail drawn by the front end.

Size and type limits carry over from Chapter 12. fileTypes goes into the picker and is checked again on the front end, and Blocks.MaxFileSize blocks once more on the server. Attached files land in the cache the same way and are deleted by the cleanup job the same way. To keep one in the handler function, the same advice applies: copy it away on the spot.

13.7 Dialogue Speaker Structure

Dialogue is a script: a record with speakers and lines, each line marked with who said it and colored by speaker. It suits “reading” cases such as interview transcripts, meeting notes, and two-person walkthroughs; it does not suit “back-and-forth Q&A” — it has no input box and no toolbar.

Figure 13-9 A script: two speakers each with their own background color, four lines in order

Three parameters decide how it looks. speakers lists who is present (and also fixes the order of the colors), type written as "list" gives one line per sentence (the default "text" is one whole block of text), and colorMap gives each person a color.

Be careful with the structure of the value. Pass in new[] { new DialogueTurn("Editor", "...") } and the UI displays a string of DialogueTurn { Speaker = Editor, ... } literals. That is because this component’s value does not go through a type — it only understands JSON. The sample therefore hands over JSON directly.

    public static JsonArray Script() =>
    [
        new JsonObject { ["speaker"] = "Editor", ["text"] = "Is the example in this section too long?" },
        new JsonObject { ["speaker"] = "Author", ["text"] = "Longer is fine, but you should be able to tell at a glance what it does." },
        new JsonObject { ["speaker"] = "Editor", ["text"] = "Then keep the callback panel so readers can compare side by side." },
        new JsonObject { ["speaker"] = "Author", ["text"] = "Keep it." },
    ];

DialogueTurn is for reading. When a handler function receives a script, the framework reads it into a list of DialogueTurn, with both the Speaker and Text fields present. Write JSON on the way in, take records on the way out; don’t get the two directions mixed up.

colorMap is the background color of the whole row, not the color of the speaker label. The sample first used dark blue and dark green, and the text blurred into the background; switching to light blue and light green brought the text back. That is the difference. Choose colors as “backgrounds”, not as “theme colors”.

The other value of type is "text", which is also the default. The whole script becomes one text area, and the user can edit it like a piece of text. That suits “let someone write a dialogue record”, not “edit line by line”. The sample writes "list", because it wants one line per sentence with the speakers kept apart.

formatter and unformatter are a pair. The former turns “your value” into the script the front end shows; the latter turns an edited script back into “your value”. Give neither and the defaults are used. The default writes one line as [speaker] line. The sample gives neither. Its value already has that structure, so there is nothing to convert.

interactive decides whether this script can be edited. It can by default. Each row has a speaker dropdown plus a text box, so the user can add, change, and delete lines. The left cell of each row in Figure 13-9 is the speaker. Write false and it is read-only, which suits “put a cleaned-up record on display”. An edited script comes back as the new value, still that same JSON array, so the code reading it does not need two versions for “edited” and “not edited”.

When should you use Dialogue rather than Chatbot? Look for a “there” and a “back”. If there is back-and-forth and the user will keep talking, it is a conversation — use Chatbot. A fixed record laid out by person is a script — use Dialogue. The former has an input box and a toolbar, the latter does not; the former splits left and right by role, the latter colors by speaker. Both are called “dialogue”, but one can grow and the other can only be read (or edited as a whole).

13.8 Chapter Summary

A message is four fields: role (three values), content (an array of blocks), metadata, and options. There are three kinds of content block: text, file, and component. So one message can hold a passage plus an attachment, or hold a table. Metadata is for the UI. Title makes it collapsible, Id/ParentId lets it nest, and Log and Duration show beside it.

The history lives in the component’s value. The handler function receives the whole list and returns the whole list, so “multiple turns” needs no extra storage; the cost is that the history travels with every request and is gone on refresh. To keep it across refreshes, you need state (Chapter 14).

Presentation has four switches. layout toggles between bubbles and full rows, renderMarkdown decides whether asterisks become bold or are shown as-is, height decides how many messages you see at once, and autoscroll governs whether a new message scrolls into view. There is also groupConsecutiveMessages, on by default and easy to forget: adjacent messages of the same role merge into one bubble.

Of the four events, like has to be bound before there are thumbs-up and thumbs-down; retry and undo appear only in the last round; edit needs editable on first. like’s Value is an array of text blocks, not a string; undo gives only the position of the user’s message, and you have to delete the assistant’s yourself. Leave it and you will see two assistant messages merge into one. All three events can return a new conversation, and all three can also just make a note.

ChatInterface buys a complete chat page in twenty lines, but it builds its own Blocks and cannot be fitted into an existing layout; like and dislike are off by default. There is only one test: if the whole app is a chat, use it; if you already have a workbench, handwrite Chatbot.

The value of MultimodalTextbox is text plus files, and its three parameters are the same set as File. Dialogue is a script, not a conversation: speakers, lines, and colors, with the value written as JSON, and DialogueTurn appearing only when you read it.

The chat block differs from the previous ten in one more fundamental way. Its value is “history”, not “a value”. That has three consequences; go over them once more before you close the book.

First, the value keeps growing. A four-message chat and a forty-message chat send data on a different scale with each request; at forty, one request has to carry the entire history. So “how many rounds to bring along” sooner or later becomes a decision you state explicitly, rather than “bring everything”.

Second, values are nested inside the value. A message holds blocks, a block holds a file, and behind the file is a cache path. Chapter 12’s rule that “paths go stale” still holds one layer of message down. That is also why a file block’s handler function has to copy the file away early.

Third, some of the buttons on the UI are not ones you placed. Like, dislike, retry, undo, and edit all come with the component; the only decision you get is “whether to bind them”. Don’t bind them and they do not appear (like/dislike) or appear with no effect (retry); bind them and you have to think through what to return.

With that, the part on interface building blocks is done. Eleven blocks sit on one page, each minding only its own value. But one page refresh leaves nothing behind, and two blocks cannot share a piece of data. The chat magnifies the problem: one refresh and the whole history is gone. The next chapter solves it — state.

Chapter 14. State and Sessions

In the previous eleven blocks, each value lives inside a single request. You fill it in, click once, get a result, then wait for the next one. To carry a value across two clicks (say “the three entries the user just recorded”), you need a variable that survives across requests to store it in.

A value can live in a component’s value, in the server-side State, or in the browser’s BrowserState. The difference between the three is not in how you write them, but in “is it still there after a refresh” and “can someone else opening it see it”.

This is harder than it looks. “Remembering” splits into three layers. Between two clicks it is the component’s value; from a page opening to closing it is the session; for a person coming back next time it is persistence. Three layers, three ways of storing; mix them up and you get all kinds of “why did it disappear” problems.

The sample adds a twelfth block to the workbench: the state module. It writes the same line into two places at once, one on the server and one in the browser, then tests them with four actions — record an entry, read both sides, refresh, and wait for it to expire. All four actions run in a real browser, and the numbers in the figures are the displayed values read after each step.

14.1 State Initial Values and Write-Back

State is an invisible component. It draws nothing, the front end cannot get its value; you declare it, put it in an event’s inputs and outputs, and that is all.

            var notes = gr.State(JsonNode.Parse("[]"), timeToLive: 30, deleteCallback: OnDropped);
            var local = gr.BrowserState(JsonNode.Parse("[]"));

The first line is server state. An empty array is the initial value, it lives 30 seconds, and OnDropped runs when it is dropped. The second line is browser state, with the same initial value and no other parameters. Neither is displayed, so they can be written anywhere in the UI. The sample puts them at the start of “State view”; readers cannot see them on the page.

Why not just use a local variable? Say you write List<string> notes = [] outside the handler functions and have all of them use it. That code compiles and runs, and then it gives itself away when a second person opens the page. That list is one per process; two users add to it and each can see the other’s entries. The “first entry” the first person recorded is there for the second person to read after a refresh.

This is the first reason state components exist: separation by session. The framework gives each session its own value, which a local variable cannot do. The second reason is that it follows the framework’s lifecycle. You can set a lifetime, get a callback when it is dropped, and have it cleared when the session ends; a static list just keeps growing.

Open the page configuration and this state contributes only two things: time_to_live is 30, and delete_callback is null (a callback cannot be written into configuration). There is no value. A state’s value belongs to the session, not the page. This is unlike every component before it: every other component has a value in its configuration, and this one does not.

What type is the value? gr.State takes a JsonNode, because a state’s value is simply a JSON tree — array, object, string, or number. When it is passed to a handler function, a JSON array becomes an object[] with one scalar per element.

(object[], object[], string, string) Remember(object[] notes, object[] local, string text)
{
    var mine = StateBook.Items(notes).ToList();
    mine.Add(text.Trim());

    var theirs = StateBook.Items(local).ToList();
    theirs.Add(text.Trim());

    return ([.. mine], [.. theirs], Panel("Server state", mine), Panel("Browser state", theirs));
}

Four return values: the two states’ new values and the text for two panels. The first two land in the states (stored, not shown), the last two in the panels (shown). Get this division clear. State is an output component too, except that its “displaying” is “storing”.

Reading and writing are declared separately, so there are three ways to use it.

  • In both inputs and outputs: read it, change it, write it back — the most common;
  • In inputs only: read-only. The handler function gets the value but cannot change it. Writing it back has no effect either, because nothing receives it;
  • In outputs only: write-only. Good for an action like “Clear”, where the handler function returns an initial value and does not need to read first.

The bindings look like this.

    memo.Add.Click(Remember, [kept.Notes, kept.Local, kept.Input],
        [kept.Notes, kept.Local, kept.Server, kept.Browser], apiName: "Record");
    memo.Read.Click(ReadBoth, [kept.Notes, kept.Local], [kept.Server, kept.Browser], apiName: "Read both");
    memo.Drops.Click(ShowDrops, null, [kept.Dropped], apiName: "View callback");

“Record” reads two states plus an input box and writes back two states plus two panels; “Read both” only reads and does not write state, so the states are not in its outputs; “View callback” reads nothing and writes only one panel.

The order has to match too. The order in inputs decides the parameter order, and the order in outputs decides where the return values go; the sample’s two states come first on both sides, so Remember’s first two parameters and first two return values are both them. Get this order wrong and there is no error, only values written into the wrong components. Write an array into a panel and text into a state and you can see it at a glance in the UI, but to track it down you have to think of this layer first.

The sample’s panel order matches the order of the two states: server panel first, browser panel second. That way, when reading the code, “which parameter goes with which output” needs no flipping back and forth — you can match them at a glance. Once there are many components, this consistency is worth more than saving a few lines of code.

Figure 14-1 shows it after clicking “Record” twice: two entries on the server on the left, two in the browser on the right, with the same content.

Figure 14-1 Two entries recorded on the same page, one copy stored in each place

The two states are written in the same block of code with the same line, and look like twins; but the only thing they share is “the way they are written”. The next four sections are all about the layer where they part company: where they live, how long they live, who can see them, and what happens when they fill up. Reading those two lines side by side is faster than reading four pages of explanation.

Why “two copies” and not “one shared list”? Because the two states are two stores to begin with. The server one is in process memory, the browser one is in localStorage; writing the same line into both is two writes. That also explains every difference that follows. They are two different things.

The initial value has a wrinkle too. gr.State’s initial value is one copy per session. Two sessions reading the same component each get their own copy; they do not share the same mutable object. So “write an empty array as the initial value” is safe, and you will not get “session A changes the array and session B changes with it”. The framework guarantees this; the app does not have to write its own clone.

14.2 State Lifetime and Cleanup

timeToLive is a number of seconds; leave it out and it is infinite, with the value kept until the session ends. The sample writes 30 so you can see it disappear within two minutes.

Its starting point is easy to misremember. It counts from the moment the value is written, not from the last read. That is, a state written once and then read every ten seconds expires 30 seconds after it was written, not “30 seconds after the last read”. This rule comes from the Python version, on the grounds that “the lifetime belongs to the value, not the session”. Two states can each have their own lifetime without affecting each other.

From that follows a finer rule: a state that has only ever been read and never written never expires, because it has no “write time” to count from. The sample’s two states start at their initial values, with nobody having written to them. If you only click “Read both”, that empty array can stay forever. To start the clock, you have to write once.

This difference matters in real applications. A “loaded model” state is written once when loading and only read afterwards, so it counts from load time and is released when the time is up. A “currently selected row” is written once per user click, restarting the clock, and only expires when the user leaves it alone. Both use the same parameter, but the meaning differs depending on how you write.

What happens when it expires? The value goes back to its initial value (an empty array in the sample) rather than becoming null or throwing. The next time a handler function reads it, it gets [], just as when it was created. So in code, “expired” shows up as “the value is gone” — no error, no notice.

To do something at that moment, use deleteCallback.

static void OnDropped(object? value) => StateBook.Dropped(value switch
{
    object[] items => items.Length == 0 ? null : items[^1]?.ToString(),
    JsonArray array => array.Count == 0 ? null : array[^1]?.ToString(),
    null => null,
    _ => value.ToString(),
});

It is called once when the value is dropped, with that value as its argument. Note that it is “the value before it was dropped”, so you can see what was stored last. The sample uses it to record one entry: how many times it ran and which item was dropped last.

That count is one per process, not one per session. It is not state, just a diagnostic number. So callbacks from two sessions add to the same number, which does not conflict with “state is separated by session” — the count never belonged to any session. That is where the line in Figure 14-2, “Drop callback ran 1 time, and the last one dropped was ‘an expiring entry’”, comes from.

Figure 14-2 Expiry: the server goes back to 0 entries, the browser still has them, and the callback ran once

The callback is good for more than counting. In a real application it is the right place for “releasing”. If a state holds a database connection, an open file, and a loaded model, dropping the value is exactly when you close them. It is the app’s one and only chance to learn that “this value is gone”.

Two things to know when using it. First, it may run on any thread. Cleanup happens in the framework’s sweep, not on your request’s thread, so anything the callback touches must be thread-safe, or the callback should only do light work like “record an entry, send a signal”. Second, it should not throw. The sweep is batched: if one callback throws, cleanup of the values behind it may be cut short. The sample’s callback only increments a counter, precisely to avoid trouble.

One more counterintuitive point: timeToLive is not a cache eviction policy. It means “this value lives this long”, not “throw it away first when memory is tight”. To control memory you use the two session-store numbers in 14.6, not a short life on every state. Mix the two and you get things like “the user is halfway through a form and the value suddenly disappears”.

Session end is another route. Closing the page does not clear the session immediately. ClosedTimeToLive defaults to one hour, leaving time for “refresh and pick up where you left off”. Past that, the session and its values are dropped together, and the callback still runs.

The two routes are “whichever comes first”: if the value expires first it takes the value route; if the session closes first, the session goes once that hour is up. So a written value lives at most until “last write + max(lifetime, one hour after close)”; a value that was never written has no starting point and can only follow the session.

One thing to keep straight: timeToLive only applies to State. BrowserState has no such parameter; its “lifetime” is decided by the browser. As long as the user does not clear the cache or switch browsers, it is always there. To give it an “expiry time” you have to store a timestamp in the value yourself and compare it when reading. The framework does not do it for you, because browser storage has no concept of expiry in the first place (localStorage, unlike a cookie, cannot carry an expiry time).

14.3 BrowserState and Browser-Side Storage

BrowserState puts the value in the browser, specifically in localStorage. That one move changes its nature.

  • It crosses sessions. Refresh, open another tab, close and reopen — the value is still there;
  • It follows the browser. Switch browsers or machines and it is gone;
  • It uses no server memory. Ten thousand users each with their own copy put no load on the server at all.

Figure 14-3 shows it after “switching to a new session”. The previous page recorded two entries; this page is a new session, so those two are invisible on the server (the server has only 1 entry, recorded on this page). All three are still in the browser, and the first two are exactly the ones from the previous page.

Switch browsers as well (Figure 14-4) and both sides start from one entry. The browser side has one entry, because it switched to a different localStorage and the first two simply do not exist in the new browser.

Figure 14-3 Switch sessions: the server starts from 0, the browser continues with the previous page’s three entries

Figure 14-4 Switch browsers: the browser side goes back to zero too

This component has two more parameters whose defaults you should know. storageKey is the key it uses in localStorage; leave it out and one is generated at random. Random is so two apps on the same domain do not collide — each reads its own.

What if two apps share a key? The one opened later reads the value the earlier one stored and treats it as its own. If the types do not match it errors; if they do match, that is worse — it carries on using someone else’s data as its own. So when running several apps on one domain, do not skip this parameter. Giving each app an explicit name is steadier than relying on the random value (the random value changes after a process restart, and the old key is left in the browser with nobody to clean it up).

secret is the key the browser uses to encrypt its own copy; leave it out and it too is generated at random. It is in the configuration because the browser needs it — both encryption and decryption happen on the browser side. So what it protects is “keeping the string in localStorage from being casually turned into a readable value”; what actually stops “changing” and “reading” is the server-side wrapper.

A random secret has a side effect too. After a restart the browser cannot decrypt its own stored copy, which is as good as losing it. To keep it across restarts you have to give a fixed secret. But then the browser layer’s encryption is effectively public (anyone can see the secret). Fortunately the server-side wrapper is unaffected — its key is not in the configuration. So “across restarts” hinges on that server key. It lives in the process, and once the process changes it is gone.

A third parameter does not appear in the signature, but it decides how this component works: the server wraps the value with a key of its own. What the browser stores is the wrapped string, which it cannot read — it simply stores it as-is and sends it back as-is; when the server receives it, it can verify “was this wrapped by the server?”. A value that was altered, or forged by the client, fails verification and is treated as the default.

So the claim “browser state can be changed by the user” is only half true. The user can change the string in localStorage, but after that the server rejects it. That is a different matter from Chapter 12’s “type limits are only for experience”: that one really has no defense, this one genuinely blocks it.

What does it defend against? An example: a state holds “which pages this user may see”. If it could be changed, the user would set it to “all” and bypass permissions. The wrapper closes that path. The client cannot compute that key; changing a single byte fails verification. But what is blocked is “tampering”, not “reading”. The user can still see their own content (by decrypting with secret), so permission data does not belong here — it belongs in server state.

There is capacity too. localStorage is on the order of a few MB per domain (it varies by browser), and once it is full setItem throws. A list of a few hundred items is fine; a cache of a few MB will fail. And the failure shows up as “it did not save”, not “an error for you to see”. So browser state suits things that are “small and need to cross sessions”: preferences, drafts, last position.

Browser state has one more detail with multiple tabs. Two tabs share the same localStorage but each has its own page memory. Tab A writes, and tab B does not know right away — it still holds what it read when it opened. To make it see the change you have to refresh, or re-read in the change event. localStorage has no “cross-tab push” of its own; for live sync you add a layer yourself (for example listening for the browser’s storage event, which is front-end work).

So “browser state crosses sessions” needs a qualifier. What it crosses is “reopening”, not “being open at the same time”. Two tabs changing it at once: the later write overwrites the earlier, the same principle as the server state in 14.5.

Open the page configuration and this component contributes three things: default_value (used when the browser has stored nothing yet, an empty array in the sample), storage_key (a random sixteen characters unless you specify one), and secret (also a random sixteen characters). There is no value either. Like State, its value is not on the page, it is in the browser.

“Server wraps, browser stores” comes down to this in localStorage: the browser gets a string of characters it cannot read, stores it, reads it back, sends it back unchanged, and never interprets what is inside. The wrapping uses the server’s key, generated at process start and never serialized. So two things hold at once: an altered value fails verification (the client cannot compute that key), and the content cannot be read either (the client has no key). secret is another layer: the browser uses it to encrypt its own copy, and even if someone uses secret to peel off that outer layer, inside is still the server-wrapped string, and the content stays unreadable.

One side effect while we are here: because the value is wrapped, the same data takes up a little more room in the browser than raw JSON (encoding plus a verification tag). It does not matter for small things, but count that layer in when you are pushing against the capacity limit.

One more easy-to-miss point: that key belongs to the process. After the app restarts the key changes, and old values stored in the browser fail verification and are all treated as defaults. So BrowserState survives refreshes and survives tabs, but not a restart. To survive a restart it would have to be server state plus real persistence — that is, a database.

14.4 Choosing Between State and BrowserState

Lay the differences above out in a table and you no longer have to guess which one to pick.

Figure 14-5 Three ways of storing, and whether each survives in six situations

The “still there or not” in the table comes from running this chapter’s sample: same machine, same browser, same run, trying refresh, a new tab, and a different browser once each.

One row in the table deserves its own look: refresh. Many people assume server state survives a refresh, since it is on the server. Run it once and you find it does not. A refresh is a new page load, hence a new session; the previous page’s values are still in memory, but the new page cannot reach them. So “still there after a refresh” is something only browser state can do.

That follows from the definition of “session”. To keep using a value after a refresh you have to put it in the browser, or use real external storage (a database plus some identifier like a session id). The former is BrowserState’s job; the latter you write yourself.

How to choose? Split it by “who does this value belong to”.

  • Temporary data belonging to this session (the few entries just recorded, a half-finished intermediate result, the currently selected row) goes in State. It follows the session and should be gone when the session is gone, takes no browser space, and the user cannot change it.
  • Preferences belonging to this person (theme, the last page opened, which panels were collapsed) go in BrowserState. They are there after a refresh and after closing and reopening the browser, with nothing for the server to remember.
  • What belongs in neither (orders, balances, things other people can see) goes in a database. None of the three ways of storing crosses machines, and none covers “switch computers and carry on”.

There is a third option that is easy to forget: do not store it. Do not store a value you can compute from something else — the current time, the length of a list, the sum of two inputs. Once stored, you have to maintain its consistency: the user changes an input and you must remember to sync the state; miss one place and two numbers in the UI no longer agree. Chapter 13’s chat is handled exactly this way. The history lives in the chat component’s value, with no extra state copy, so there is no “two copies disagreeing” problem.

One more kind is most often misused: treating State as storage. It looks handy (a dictionary, put anything in it, and it crosses events), but it does not survive a restart, nor the hour after a session closes. Store “the user’s history” in it and the day after launch you get feedback saying “the records are gone”. That is what the last line of this section — “to cross machines, cross browsers, cross restarts, all three fall short” — is about.

Another common mismatch is the reverse: putting something that belongs on the server into the browser. Take “is this user an administrator?”. Browser state can be read and changed by the user (changed values are rejected, but reading is possible), so putting identity information in it is like pinning the permission table on the door. The test is simple: would it be a problem if the user saw this value? If yes, put it on the server.

When you actually choose, ask three questions in this order.

  1. Does this value need to survive a refresh? If not, use the component’s value; you do not even need to create a state.
  2. Yes, and only this page uses it? Use State.
  3. Yes, and the user wants to see it next time they open the app? Use BrowserState, provided it is something the user may see.

If it fails all three, then it is “cross machines / cross restarts”, and it belongs in a database.

14.5 The Practical Boundaries of Session Isolation

How are sessions divided? The result of running it is this: one session per page load. A refresh is a new session, and so is another tab. So in Figure 14-3 that new page starts server state at 0. It never saw the previous page’s values at all.

Technically, when a page first connects the server gives it an identifier, and every request after that carries it back; change the page and you change the identifier, so naturally you cannot read the previous session’s values. How that identifier is carried and where it is stored is an internal framework matter the app does not need to know. But “one identifier per page” is what determines everything below.

Where did the previous page’s values go? They are still in server memory, attached to a session nobody will ever visit again. They are cleared only when one of two things happens: its lifetime runs out (if timeToLive was set), or the hour after the session closes runs out. So “old values vanish immediately after a refresh” is an illusion; what changes is only “whether they can be read”.

This boundary needs stating clearly, because the word “session” makes people think of a browser window or a logged-in user. In this framework it is closer to “one page load”. Two tabs in the same browser are two sessions; a refresh is another session too.

So “two sessions do not share state” is verified in the sample like this: the first page records two entries, and the second page sees only the one it recorded itself. The second page did not “clear” the first. The first page’s values are still in server memory, just with nobody pointing at them; only when its lifetime runs out, or the hour after the session closes runs out, are they dropped.

The screenshot in Figure 14-3 is exactly that verification: only one entry on the server on the left (recorded on this page), three in the browser on the right (the first two from the previous page). Same code, same component, and the new session cannot see the previous session’s two entries. This is the most direct evidence of “isolation” — no logs to read, no inference needed. What it checks is “after the previous session closed”, not “two tabs alive at the same time”; the latter can also be checked with the sample (open two tabs, record one entry in each, read each), it just cannot be captured in one screenshot.

Verifying it yourself is easy too. Open two tabs, record one entry in each, and click “Read both” in each. On the server side each sees only its own entry; on the browser side both see everything (because they share the same localStorage). That difference is exactly the one from 14.3: server state is divided by session, browser state by browser.

Inside a single session there is one more boundary: reads and writes are not a transaction. Two events run at once, both start from the same old value, each adds its own entry, and both write back. The later write wins, and the earlier entry is lost.

Take a concrete case. The state holds ["a"]; two handler functions run almost simultaneously, both read ["a"], one adds b giving ["a","b"], the other adds c giving ["a","c"]; two writes come back and the latter is what remains. b is gone. This is the inevitable result of “one value per session”: both writes “replace the old with the computed result”, with no merge step.

To serialize them you have to make them queue up. That is what the concurrency limit in Chapter 15 is for. Or simply do not let two events write the same state. Make “Record” a single action: two user clicks are two requests, and the queue handles them in order without concurrency. The sample does the latter — one button, one write.

One more boundary that is easy to confuse: a session is not a user. The same user opening two tabs gets two sessions with their own state; opening on another computer is two sessions again. The framework has no concept of “user” — that belongs to authentication (Chapter 20) and the database. So a requirement like “remember this user” cannot be met with state; it needs a real identity.

When does a session count as “closed”? Once the page is closed, the front end’s long-lived connection drops, the framework takes that as the session ending, and starts the one-hour countdown. The detection can be a few seconds late (connection timeout), or misjudge once because of a refresh. On refresh the old connection drops and a new one is built, which looks like “closed and opened again”. That is why an hour is kept after closing: better to hold on a little longer than to wipe values while the user is refreshing.

14.6 Session Store Capacity and Expiry

A session and its values live in a “session store”. The default implementation is a dictionary in memory, and two numbers decide its size.

  • Capacity. How many sessions to keep at most, 10000 by default. Past that it drops the least recently used one. “Least recently used” means “not accessed for the longest time”, nothing to do with age.
  • TimeToLive. How long a session may sit idle before it expires; unset by default, which means never.

Both numbers live in SessionStoreOptions. gr.Launch() uses the defaults, so the sample runs on the defaults too; to change them you go through host registration (Chapter 21). The options.SessionStore inside AddGradioCore is it — set the two properties directly.

Why not add two parameters to gr.Launch()? Because the session store can be swapped out wholesale. The in-memory implementation suits a single machine; a multi-instance deployment needs shared storage (say Redis). SessionStoreOptions is two numbers for people “using the in-memory implementation”; swapping the implementation is a different matter, done through dependency injection. Keeping the two apart is what stops the interface from bursting with parameters. The in-memory implementation alone is enough for this chapter.

The capacity number looks large, but a quick calculation tightens it. Ten thousand sessions, each holding a hundred-item list, is a million records resident in memory; at a hundred bytes each, that alone is a hundred megabytes. Multiply by each session’s own overhead (connection, configuration copy, remembered component values) and even an app “nobody uses” can take up several hundred megabytes.

So capacity and state size are a pair. With small things in state, ten thousand is generous; with large things, that number has to come down. Turn it down and the behavior is “drop the least recently used session” — a session, note, not a single value. When a session is evicted, all of its states go together, and deleteCallback still runs (it is the notice that “a value was dropped”, whatever the reason). So the resource-releasing code in the callback runs in all three cases: “expired”, “session closed”, and “evicted”. That is exactly why it is more reliable than “manual cleanup elsewhere”.

TimeToLive is another ruler: how long a session may be idle before it expires. Leave it unset and a user who walks away with the page open leaves the session sitting there until capacity fills and it is evicted. Set it to, say, half an hour and an abandoned session is reclaimed after half an hour, so memory is not filled up by “opened and never closed” tabs. Tuning both numbers together is what counts as “under control”: capacity governs the upper bound, idle expiry the lower bound (how long before an unused one is let go).

These two numbers have an easily confused neighbor: ClosedTimeToLive, the “keep for one hour after the session closes”. It is a property of each session, not a setting of the store, and cannot be tuned from here. You can remember the three like this: TimeToLive governs “the person is still here but stopped using it”, ClosedTimeToLive governs “the person left but may come back”, and Capacity governs “there are simply too many, which goes first”.

The sample runs on the defaults, so it cannot demonstrate “capacity full, session evicted”. That would need ten thousand sessions, all open at once. This tier can only be covered by reading the contract and doing the arithmetic; there is no button to click. That is where this tier’s boundary lies: demonstrate what can be demonstrated, and for what cannot, say plainly that it is a contract — do not pretend you have seen it.

One last note on why the defaults are so generous. Ten thousand sessions with no expiry is the “get the app working first” setting. For local development or a small internal team, nobody ever hits the limit. Before a real launch, recalculate both numbers against your own concurrency and the state size per session; if the calculation says to change them, change them in the host registration.

14.7 Chapter Summary

State is a server-side, invisible component. Its value never reaches the page; a handler function receives object[] (a JSON array), and putting it in outputs is “storing it”. The initial value is one copy per session; timeToLive counts from the write and returns to the initial value on expiry; deleteCallback is the app’s one chance to learn “the value is gone”, which makes it the right place for resource-releasing code.

BrowserState puts the value in localStorage. It crosses refreshes and tabs and follows the browser; the server wraps it with a process-level key, and an altered value that fails verification is treated as the default; after an app restart the key changes and old values are no longer recognized.

The three ways of storing each have their own lifespan. A component’s value lives one request, State lives one session (plus the hour after close), and BrowserState lives until this browser is replaced. To cross machines or restarts, all three fall short.

Sessions are divided by page load. A refresh and a new tab are both new sessions, so server state “disappears” in both cases; two sessions record their own entries without interfering. Concurrent reads and writes within one session are not a transaction — the later write wins.

The session store has two numbers: capacity (ten thousand by default, dropping the least recently used past that) and idle expiry (never by default). They live in SessionStoreOptions and are changed through host registration.

Three things from this chapter.

  • A component’s own value lives one request and is gone on refresh. It is the input and output of “this operation”, not memory.
  • State lives one session (plus the hour after close), divided by page load; its value is on the server, invisible and unchangeable to the user; on expiry it returns to the initial value, and deleteCallback is the only notice.
  • BrowserState lives until this browser is replaced, divided by browser; its value is in localStorage and the user can see it (so do not put secrets there), altered values are rejected, and after an app restart the old values are no longer recognized because the process key changed.

One more thing they share: none of the three is persistent. To cross machines, restarts, and users you have to connect a database yourself. What the framework gives you is “remember within a session”, not “save forever”.

By this chapter, every block of the workbench can remember its own things. What is still unsolved is “ten people arriving at once”. The next chapter covers queues and concurrency: whether requests queue up, how many run at the same time, and what happens when that is exceeded.

Chapter 15. Queues and Concurrency

Up to the previous chapter, every block of the workbench could remember its own things. But one question has been left until now: what happens when ten people arrive at once.

One handler function runs slowly, a second person clicks the same button — do both run, or does one wait for the other? Ten people click at the same time — do they line up in a queue, or are they rejected on the spot? What we are talking about here is behavior, not “performance optimization”. After the user clicks, what they actually see is “queuing”, “computing”, or “application busy”.

Without a queue, every click immediately starts an execution. Ten people clicking at once means ten running at once; the hundredth person clicking means a hundred. The server’s threads, memory, and downstream database connections cannot hold up under that. The job of a queue is to funnel this flood into one (or a few) controllable pipes. There is a fixed number of how many can run, and when too many are waiting, they get blocked.

How events are queued, how many can run at once, what happens when too many are waiting, and one place most likely to make all of the above fail together — the handler function is written badly.

The sample adds a thirteenth block to the workbench. The queue module: five slow tasks in two groups, one release button, one batch button. The slow tasks do not pretend to be slow with Thread.Sleep; they wait for a “release” instead, and the release is given by another event. So “exactly how many are running at the same time” is something you can read from the log, no guessing.

This design is how this chapter verifies things. You can also see concurrency with a fixed wait (say each task sleeps two seconds), but that experiment is unreliable — if the machine is busy for a moment within those two seconds, the conclusion changes. Waiting for a “release” is different. You decide when a task moves; whether it is really running at the same time depends only on whether the “entry” and “exit” times overlap.

15.1 Queue and Event Execution

By default, an application comes with a queue. You write no code for it. Every click, every submit first enters the queue, and the queue decides when it runs.

Figure 15-1 The path an event takes through the queue: entering, waiting, taken by group, executing

Figure 15-1 has three gates, each with its own job,

  • Queue limit (maxSize), how many events can be waiting at once;
  • Concurrency group (concurrencyId). Bindings in the same group share one “how many run at once” limit;
  • Concurrency limit (concurrencyLimit), what that limit actually is, as a number.

The three parameters are written at two levels. The queue limit and the default concurrency go on the application-level Queue(...); grouping and a single event’s concurrency go on the binding’s Click(...). Which level you write it at decides how wide a scope it controls.

The three are independent of each other. The queue limit governs “those waiting”, the concurrency limit governs “those running”. When one is full, it rejects; when the other is full, it waits — two completely different behaviors.

When the queue picks up a task it has to pass the concurrency group first. Each time it picks one from a group that “still has a free slot”, which group it picks and which item within the group are not guaranteed to follow arrival time. So do not count on “first in, first out”. Within the same group the earlier one runs first; between different groups there is no order. This detail explains why A’s second task keeps waiting while B, which arrived later, can run first.

Each event gets a number when it enters the queue, and the front end uses that number to ask “what position, how much longer”. rank is the position (0 means next), rank_eta is the estimated wait in seconds, queue_size is the total number waiting in the whole queue. The estimate is rough. It is computed as “how many ahead × average duration”, so a single unusually slow task throws it off.

The queue’s state can be queried. /gradio_api/queue/status returns a snapshot.

{"msg":"estimation","event_id":null,"rank":null,"queue_size":3,"rank_eta":null}

When two slow tasks are waiting and one is running in the sample, queue_size is 2. It is the number “waiting”, not counting the running one, and it never exceeds the queue limit. The queue counts this number itself.

There is another limit not shown in the figure. The whole queue runs at most 40 at once; that is the default, and the application can change it. On a standalone host you write Launch(maxThreads: 8); when you plug into an existing ASP.NET Core host with AddGradio, you write AddGradio(options => options.MaxThreads = 8). It is larger than any single group’s concurrency limit, so you rarely hit it; but the question “I set unlimited, why does it still run in batches” usually has its answer at this level.

40 is not a thread count. Tasks in the queue run asynchronously; one thread can carry several tasks (yielding while waiting on IO). What it limits is “how many jobs are in hand at once”. No matter how many concurrency limits you add up, they cannot exceed it. If you really need to loosen it, raise this number first, then check whether memory and downstream can take it; if you raise it past a hundred and still see queuing, think about multiple processes and multiple instances rather than adding more parameters.

The queue is on by default. To turn it off for one kind of event and let it bypass the queue and run directly, you write queue: false at the binding. That is for “small actions that do not need queuing” (say changing a single label). This chapter does not expand on it; Chapter 5 mentioned it in passing when it covered events.

The consequences of turning the queue off need to be clear. That event is no longer bound by the concurrency limit or the queue limit: one click starts one, a hundred clicks start a hundred. What you get in exchange is “immediacy”. The front end does not wait in the queue and gets the result at once. So queue: false only suits actions that “take almost no time” — changing a label, toggling a panel’s visibility. Any action that touches files, the network, or a database should not turn it off.

One more easily overlooked thing: the queue is application-level, not page-level. This is especially obvious in a multi-page application (Chapter 18), where a slow task on one page occupies a slot on another. All events of the same application (no matter which module or page) share this one queue and this one limit. So “the queue module is stuck and the other modules cannot be clicked either” is by design.

15.2 The Default Concurrency Limit

Write no concurrency parameter at all — how many can one binding run at once? One. This answer is more conservative than many people expect. After all, the default gives the impression of “handling several requests at once”. But for a handler function, “running one at a time” is the state least likely to go wrong, and the framework chose the conservative end.

You can see the effect of this default with two clicks: the second has to wait for the first to finish. What the user sees is “I pressed it and nothing happened, then it moved a moment later”. If the first run is slow, the experience is “it is stuck”.

Why is the default 1 and not “unlimited”? Because 1 is the safest starting point. When a handler function is called twice at the same time, the most likely problems are shared state being trampled (both read, both write, the later write overwrites the earlier) and downstream being overwhelmed (both query the database, the connection pool is not enough). 1 keeps both risks outside the door, and the cost is only “a bit slower”. The criterion for choosing a default is “even if it is wrong, nothing bad happens”, not “fastest”.

When should you raise it? Look at what the handler function is waiting on. If it is waiting on the network, on disk, on downstream (that is, IO-bound), raising it pays off. Open a few more and other tasks can run during that waiting time. If it is computing, transcoding, compressing images (CPU-bound), raising it does not pay off — the machine only has those few cores, opening more just makes each one slower and uses more memory. This judgment matters more than memorizing the parameter. Set the concurrency limit by “what it is waiting on”.

After raising it, watch two things. Memory (every running task holds its own copy — images, arrays, models all live in memory) and downstream (database connection pools, rate limits of third-party APIs). You relaxed your side of the application, but downstream may not be able to take it. Throttling belongs upstream, but your application is the one that gets blamed.

Verifying this yourself is simple. Set one binding to a limit of 1 and another to a limit of 2, click each twice, and look at “how many were running on entry” in the log. The group set to 1 is always 1, the group set to 2 reaches 2. The sample’s A and B groups are exactly this comparison; change the number in ConcurrencyLimit.Of(2) and run it once to see.

ConcurrencyLimit has three states, not one number.

  • ConcurrencyLimit.ApplicationDefault. Use the application default (that is, 1); if you write nothing, this is it;
  • ConcurrencyLimit.Of(n), at most n;
  • ConcurrencyLimit.Unlimited, no limit.

Why not a single int?? Because null already means “use the default”, so “unlimited” has no value left to represent it. Three states, three values — someone reading the code does not have to guess which meaning null has.

The n of Of(n) must be greater than zero; writing 0 or a negative number throws. To “not allow it to run”, do not use 0 — use the opposite of Unlimited, that is, do not bind this event at all.

Where does the default 1 come from? There is also an application-level “default concurrency limit”, which Queue(defaultConcurrencyLimit: ...) can change. The sample does not change it, so every binding that writes no concurrencyLimit is 1; one that writes its own uses its own. The relationship between the two levels is “binding level overrides application level, application level overrides framework default”.

Use Unlimited with care. It means “run as many as come”, and the queue has no effect on it. The limit gate might as well not exist for it. Scenarios that truly need it are rare. A purely read, extremely fast, stateless interface, say “get the current time”. In every other case, writing a large number (say 8) is safer than writing “unlimited” — the number is one you thought about, unlimited is one you did not.

15.3 Concurrency Groups and Binding-Level Throttling

The concurrency limit is counted per group. The group is given by concurrencyId; if you do not give one, the binding’s own name is used.

The sample’s five slow tasks are split into two groups.

    queue.A1.Click(() => Slow("A1"), null, [lines.Runs], apiName: "A1",
        concurrencyLimit: ConcurrencyLimit.Of(1), concurrencyId: "A");

A1, A2, and A3 all write concurrencyId: "A" with a limit of 1; B1 and B2 write "B" with a limit of 2.

  • Click A1, A2, A3. Only one runs, the other two wait — they compete for the same slot;
  • Click B1, B2. Both run together; the group has 2 slots;
  • A and B do not affect each other; A being full does not hold up B.

Figure 15-2 is the log from this experiment. Four tasks belong to A, A, B, B respectively; clicked one after another, the “running” count on entry climbs from 1 to 3. A peak of 3 means three were really running at the same time, while the fourth kept waiting.

Figure 15-2 Concurrency across three groups: A1, B1, and B2 running at the same time, peak 3

Every row in the log has entry and exit times. Put the times together and three rows overlap. While A1 is still running, B1 and B2 both entered. This is the hardest evidence of “concurrency”. What you look at is whether the times overlap.

There is a trick to reading this log: do not look at the “peak” number, look at the time. The peak is a result, the time is the process. If rows join head to tail (one exits, the next enters), that is serial; if a later row’s “entry” is earlier than the previous row’s “exit”, that is parallel.

Two things hold at once in Figure 15-2. When B1 and B2 entered, A1 was still running and the three rows’ times overlap — that is parallel. And A2 is the last to enter; when it entered, A1 had just exited, the same group has only one slot, and it waited until a slot freed up — that is queuing. Seeing both things in one figure is exactly what this section is about: the limit is counted per group, queuing within a group, parallel across groups.

This way of “proving concurrency with timestamps” is far more reliable than “it feels faster”. Real performance acceptance uses the same method. It does not look at a single run’s duration (affected by machine load); it looks at whether there is overlap.

The slow task itself is written like this.

async Task<string> Slow(string who)
{
    var run = QueueDesk.Enter(who);
    var released = await QueueDesk.WaitAsync();
    QueueDesk.Leave(run);

    return $"**Log** {who} run {run.Id}: {run.Concurrent} running on entry, peak {run.Peak}, {(released ? "released" : "timed out")}.\n\n{string.Join("\n", QueueDesk.Lines())}";
}

Enter logs an “entry”, await WaitAsync() waits for the release, Leave logs an “exit”. What it waits on is a semaphore, not Thread.Sleep.

The point of grouping is “different kinds of work each queue up separately”. In one application, exporting a report and saving a draft are two kinds of work. The former is slow and uses resources, the latter is fast and must be immediate. Put them in the same group and when export fills up, the draft cannot be saved either; split them into two groups, give each its own slots, and neither holds up the other.

What happens if you do not give concurrencyId? The group name is computed from “handler function + the target that triggers it”. The same handler function bound to the same button counts as one group; bound to two different buttons, it counts as two groups. So even if A1 and A2 do the same thing, as long as they do not write the same group name, they each run up to their own limit. This is often the real reason “the concurrency limit does not take effect”. The concurrency limit constrains one particular button.

This also explains why A2 did not enter in Figure 15-2. It competes with A1 for the same slot; as long as A1 does not leave, it keeps waiting in the queue. A queue has no concept of “cutting in line”. Within the same group, the earlier one runs first, the later one waits. How long? Until the one ahead finishes. How long is that? It depends on the handler function. So a group’s concurrency limit actually decides “how many tasks’ worth of time a user of this group waits at most”.

So the granularity of a group should follow resources, not buttons. Several bindings that use the same database, the same model, and the same external interface share one group name. They compete for the same resource, so they should share one limit. The other way round, do not force two unrelated kinds of work into one group. Doing so ties their speeds together — one slows down and the other waits along with it.

The sample deliberately gives group A three buttons. A1, A2, A3 — all the same group, all the same limit of 1. So click three and only one runs. They compete for one slot. Group B gives two slots and two buttons, so clicking two makes two run together. This comparison is the point of this section. The limit is counted per group, not per button.

15.4 The Queue Limit and Over-Limit Rejection

The concurrency limit governs “how many run”, the queue limit governs “how many wait”. Queue(maxSize: 2) means at most two can be waiting, and the third is rejected on the spot.

demo.Queue(maxSize: 2);

“Rejected on the spot” is not “silently dropped”, nor “waiting forever”. It returns an error on the spot. When you go through an API call, this is the sentence returned.

{"detail":"Queue is full. Max size is 2 and size is 2."}

When you go through the UI, it pops up a different sentence, This application is currently busy. Please try again.. The two sentences mean the same thing but are worded differently. One is for a program to read (it carries the limit and the current count), one is for a person to read.

Figure 15-3 shows what it looks like when the queue is full: A1 running, A2 and A3 waiting, and at this moment you click B1 — an “application busy” notice pops up in the top right, and a red “error” marker appears on the log panel.

Figure 15-3 When the queue is full, the click is rejected on the spot and the UI says “application busy”

Two things need to be told apart here. Queuing is normal (the first person is running, the second waits), rejection is protection (too many are waiting, and waiting any longer only makes everyone slower together). A queue with no limit keeps growing until memory or patience runs out first; with a limit, at least the rejection is explicit and retryable.

maxSize counts “those waiting”, not “those running”. So maxSize: 2 plus a concurrency limit of 1 actually holds “1 running + 2 waiting”. This detail affects how you estimate the number. First think clearly about “how many people at most may wait”, then write it; do not treat it as “total number of people”.

On that rejected click, the user sees “application busy” and the handler function is never called at all. This matters. The rejection happens before entering the queue, not as an exception thrown inside the handler function. So writing “retry logic” in the handler function is useless. It was never called. To retry, you have to do it on the user’s side. Click once more in the UI, or send once more from a script.

Retrying has its own rules too. An immediate retry is usually still full — the tasks in the queue have not left yet. The right approach is to wait a while and try again, with a limited number of attempts. Three times, one second apart, is better than “retrying forever”. A client that never gives up will pin down an already overloaded application. What it produces is exactly the pressure that kept it out in the first place.

For a script caller, this error is an HTTP 400-level rejection whose response body carries the reason. When you write a client, check for this one and give the user a “try again later”, instead of treating it as “processing failed”. The two mean different things to the user. One is “not your turn yet”, the other is “it ran but did not succeed”.

To find out how many are queued right now, ask /gradio_api/queue/status; queue_size is the total number waiting. This interface needs no session, so a single script can query it. It is just right for monitoring. If queue_size stays close to maxSize for a long time, it is time to raise concurrency or add machines.

The rejection notice carries the limit and the current count (Max size is 2 and size is 2), which is there for you to troubleshoot with. When you see those two numbers equal, you know the queue is full, not that something else went wrong.

If you do not write maxSize, it is unlimited. For local development with one user, unlimited is fine; when you serve the outside world, you must set it. This is the first gate of “do not let the application be dragged down by its own queue”.

What value is right? Look at two numbers. One is “how long a wait you can accept”, the other is “how much memory each waiting task takes”. The more people waiting, the longer users wait, and the more the server has to remember (each event has its own input parameters attached). For an internal tool with only a few users, take 5 to 10; for one open to the public, prefer small over large. Rejecting early is better than letting everyone wait together until timeout.

The sample sets it to 2 so that you can see a rejection in one go. The side effect is that while those slow tasks in the queue module are stuck, other buttons on the page get rejected too. Because the limit is one per whole application, not split by module. This is not a bug; it is exactly what “limit” means.

But one kind of button must be an exception: “Release” and “Clear log”. When the queue is full, if even the release has to queue, that is a deadlock. The waiting tasks need a release to leave, and the release needs to queue to get in. The sample writes these two bindings as queue: false so they bypass the queue and execute directly.

    queue.Release.Click(ReleaseOne, null, [lines.Runs], apiName: "Release", queue: false);
    queue.Reset.Click(ResetRuns, null, [lines.Runs, lines.Batch], apiName: "Clear log", queue: false);

This is the situation where queue: false is really meant to be used: an escape valve. It does not take part in queuing and is not bound by the concurrency limit, so it can always be clicked. The premise is that it really is fast. A release just increments a semaphore, a clear just clears a table — neither takes any time. Letting a slow action bypass the queue is the same as tearing out the limit gate.

15.5 Status Push Interval

The queue’s state (what position you are, roughly how much longer) has to reach the front end before anything like “Queued, position 3” can exist. There are two ways to send it, decided by Queue’s statusUpdateRate.

  • Write nothing (the default), push on change. When an event enters or leaves the queue, or a task starts or ends, it recomputes once and pushes; when nothing happens, it does not push. This is the default, and the hassle-free choice. When the queue position changes, the user sees it right away.
  • Write a number of seconds, push at an interval. It pushes once every that many seconds, whether or not anything changed.

When do you want the latter? When the status stream is expensive — say several hundred events are queued and every movement recomputes the estimates of all positions, which costs a lot; pushing by the second keeps the cost under control. The price is “half a beat behind”. The position the user sees may be one interval behind reality.

There is a more practical reason too, when there are many front-end connections. “Push on change” means every movement of the queue pushes a message to every connected page; with a hundred pages connected, every task the queue completes is a hundred messages. Pushing by the second is one batch per second no matter how many pages. The cost changes from “proportional to the number of events” to “proportional to the number of seconds” — a completely different order of magnitude.

This parameter’s name is easy to misunderstand. statusUpdateRate sounds like “the rate of status updates”, but it only takes effect when you are “not pushing on change”. To keep “push on change”, do not write it; to switch to pushing by the second, write a number of seconds. The two modes are an either-or choice.

Why is “push on change” the default? Because most uses of a queue are “a few people”, where state changes are infrequent, so pushing on change is both hassle-free and fresh. Pushing by the second is for “many people”. At that point the cost of “fresh” is too high, so being half a beat behind is preferable. This trade-off is the same kind as maxSize in 15.4. At small scale, do whatever is comfortable; at large scale, you have to do the math.

The sample does not change this item and runs on the default. This setting does not show up in screenshots. A single frame cannot capture “rhythm”, just as a photograph cannot capture a heartbeat. What can be said is its effect. With the default, you click a button and the queue position changes immediately; set it to 3 seconds and it changes only at the next three-second mark.

To verify it yourself, open two tabs. In one, click a slow task to hold it up; in the other, click a few times and watch when “Queued, position N” changes. In the default mode it changes every time an event enters; switch to pushing by the second and it jumps on a fixed rhythm. This experiment needs no code changes, just one line changed to Queue(statusUpdateRate: 3).

So for this “status push interval” parameter, reading the contract is more reliable than looking at screenshots. Its effect is “how often it changes”, while a screenshot only has “what it is right now”. For evidence, use two tabs with a stopwatch, or capture a stretch of the status stream and count the messages.

There is one thing in the queue’s state that “looks like it but is not”: the progress reported by the handler function itself. Both show a progress bar in the UI, but one is “how many people are ahead of you” and the other is “what percentage of this job is done”. The former is computed by the queue, the latter is reported by the handler function (Chapter 16). Mix the two up and you get “a progress bar that jumps back and forth”, because the two sources are fighting over the same display slot.

15.6 Batching and Batch Size

There is one more way to make the queue more worthwhile: batching. Collect several events and merge them into one call.

    queue.Batch.Click(BatchRun, [queue.Value], [lines.Batch], apiName: "Batch run", batch: true, maxBatchSize: 3);

batch: true turns it on, maxBatchSize: 3 says it collects at most three at a time. Once it is on, the handler function’s signature changes. It is no longer “one value” but a batch of values, object[].

string BatchRun(object[] values) => "**Batch** " + QueueDesk.Take(values);

When does it collect? When several events for the same binding are queued. Three requests arrive almost at the same time, the queue merges the three into one call, and the handler function receives one object[] with three values inside. What you save is “the fixed overhead of each call”. Opening a connection, loading a model, starting a transaction — once versus three times is a big difference.

To be concrete, a hundred records need a database lookup. Without batching that is a hundred round trips; batched into ten batches, it is ten. Say the network latency of each round trip is 2 milliseconds: the former is 200 milliseconds on the wire alone, the latter 20. What you save is “waiting”. Batching pays off most for “operations with a fixed overhead” and barely at all for “pure CPU computation”. Add three numbers up and the total CPU is the same whether you compute once or three times; batching only saves “the call” itself.

maxBatchSize is “how many at most in one batch”. Write 3 and it collects at most 3; when a 4th comes in, the first 3 go as one batch and it starts a new one. Write it too large and the first user waits a long time; write it too small and you save almost nothing. There is no formula for this number — it depends on your own tolerance for latency.

Run it once and you can see it. Three concurrent requests merge into one call, and the array the handler function receives holds three values. What to watch out for is that order is not guaranteed. That time it received v3, v2, v1, the reverse of the order sent. Batching suits scenarios where “several values are independent and handled the same way” (batch transcoding, batch database lookups), and not scenarios where “order matters” — do not turn it on for those.

What “order is not guaranteed” looks like in code is as follows. In a batch handler function, do not assume “the first element arrived earliest”. To process in order, carry a sequence number or timestamp in the value and sort it yourself when handling. This is exactly the opposite of Chapter 13’s “the array order is the UI order”. There, order is a contract; here, order is an accident.

The return value has to change along with it too. Be careful when pairing batching with state. One call handles three values, but there is only one state. If all three values need to be written into the same state, you have to loop through the writes within that one call. What you write is “the final state after this batch”. If each value needs “read state, modify, write back”, batching squeezes them into the same call and you lose the semantics of processing them one by one. Do not turn batching on for this kind of scenario.

The input of batching is object[]; what about the output? If you handle three at once and only want to return one result, return one; if each needs its own, return an array. The sample returns just one sentence (“3 in this batch. …”) because it is only demonstrating that “they were collected”. Real batching usually “returns one summary per batch”, or returns nothing at all (write it into the database and you are done).

Batching has a cost too. Handle three at once and the first user has to wait until all three are collected (or until maxBatchSize is reached) before starting; if they cannot be collected, it keeps waiting until some other mechanism lets it out. So the choice of batch size is a trade-off between “throughput” and “latency” — larger is more economical, smaller feels more responsive.

Batching is not easy to trigger from the UI. A button is disabled after one click, so you cannot produce a second event. To really try it, open two tabs and click at the same time, or fire several requests concurrently through the API. The sample’s “Batch run” button is mainly so you can see the signature: it accepts an object[], not a single value.

This also shows who the real user of batching is. “One person clicking repeatedly” does not count; “many people clicking at once” or “a script submitting in bulk” does. The former can never be collected in the UI (the button gets disabled), the latter is where batching shines. So when deciding whether to turn batching on, look at “will this interface be called concurrently”, not “will the user click repeatedly”.

15.7 Chapter Summary

The queue is on by default. Every event first enters the queue, which then decides when it runs. The three gates each govern one thing. maxSize governs how many are waiting, concurrencyId governs how they are grouped, and concurrencyLimit governs how many run at once. The parameters are written at two levels. The application-level Queue(...) sets the queue limit and the default concurrency; the binding-level Click(...) sets which group a single event belongs to and how many can run.

The default concurrency limit is 1, which means one binding runs only one at a time. ConcurrencyLimit has three states: use the default, at most n, and unlimited. It uses three values instead of one int? because null already means “use the default”.

Concurrency is counted per group. Bindings in the same group share one limit, different groups each queue up separately. The sample’s group A has 1 slot and group B has 2; click three tasks and the “running” count on entry climbs from 1 to 3, which is the hardest evidence of concurrency.

When the queue is full, it rejects on the spot rather than queuing silently. The API returns Queue is full. Max size is 2 and size is 2., and the UI pops up “This application is currently busy. Please try again.”. The limit is one per whole application, not split by module.

Queue state pushes on change by default, and can be changed to push by the second. This setting does not show up in screenshots and can only be read from the contract; what you can observe is its effect — how fast the queue position refreshes.

Batching collects several events into one call, the handler function accepts an object[], and maxBatchSize sets how many at most in one batch. What it saves is the fixed overhead of each call; the cost is that the first user has to wait until the batch is collected, and order within a batch is not guaranteed. When deciding whether to turn it on, look at “will this interface be called concurrently”, not “will the user click repeatedly”. There is a more direct criterion too. Does the handler function have “a fixed cost paid on every call”? If it does (connecting to a database, loading a file, calling a remote service), batching can save it; if it does not (pure computation), batching only piles up latency.

Beyond the four parameters there is one more use: the concurrency limit can serve as a lock. When the same state is written by two events, put the two events in the same group with a limit of 1 and they become serial. It is simpler than adding a lock in your own code, and more reliable too (forgetting to release a lock deadlocks, a queue does not).

There is one easily overlooked pairing: the queue and state are used together. If two events of the same session run at the same time, they read the same state and the later write overwrites the earlier one (as said at the end of Chapter 14). The queue’s concurrency limit happens to prevent exactly this. Put the two events in the same group and set the limit to 1, and they become serial, so the state does not get trampled. This is the second use of the “concurrency limit” besides throttling: locking shared state.

The last point is not in the parameters, but it matters more than they do: write the handler function asynchronously. The sample’s slow task awaits a semaphore, so three really run in parallel; switch to synchronous blocking (Thread.Sleep or .Wait()) and the three line up strictly one after another. The concurrency limit is still there, but the slots never free up. This is the easiest place to go wrong in this chapter. The parameters are all correct, the way it is written is not, and the behavior changes completely.

An event enters the queue (15.1) → the group decides who runs first (15.3) → the limit decides how many run together (15.2) → too many waiting and it is rejected (15.4). Every link on this chain has a parameter, but what decides the behavior is whether the handler function is asynchronous. That belongs to how you write it, not to the parameters; write it wrong and all four parameters above are tuned for nothing.

The next chapter refines this “waiting”. It has the handler function emit results frame by frame while it computes, instead of only when it is done.

Chapter 16. Streaming Output and Progress

What does the UI look like for a handler function that takes ten seconds to run? The answer from the previous fifteen chapters is “nothing moves, then everything appears at once after ten seconds”. During those ten seconds the user does not know whether the click registered or how much longer it will take, and most people click again.

In these ten seconds, results come out as they are computed, progress is reported as it advances, and timed actions fire on their own. Finally you connect a real model service and join the “pieces that come back one at a time” into text that appears on the UI a segment at a time.

The sample adds a fourteenth block to the workbench. The streaming module: one streaming run, one run with progress, a timer, and an input box for asking the model.

16.1 Async Handler Functions and Streaming Output

An ordinary handler function is “in once, out once”. A streaming handler function is “in once, out many times”, written by returning an async sequence.

async IAsyncEnumerable<string> StreamRun()
{
    var text = "";

    for (var i = 1; i <= 6; i++)
    {
        await Task.Delay(400);
        text += $"Segment {i}.";
        yield return text;
    }
}

Six yield returns are six frames. Figure 16-1 places the three approaches on three timelines. A one-shot return is “empty at the front, everything in the last cell”, streaming output is “each cell has one more segment than the last”, and progress reporting is “the content does not move, only the percentage updates”.

Figure 16-1 Three approaches, three timelines

The binding is the same as for an ordinary handler function: one button, one output. You do not need to declare “this is streaming”. When the return type is IAsyncEnumerable<T>, the framework knows to send it out frame by frame.

Figure 16-2 shows the stream halfway through: the panel holds “Segment 1. Segment 2.” and a thin progress bar is running along the top.

Figure 16-2 Halfway through the stream: the panel holds the segments produced so far, with a thin progress bar along the top

Figure 16-3 shows the stream finished: six segments joined together, with no duplicates.

Figure 16-3 Stream finished: the last frame is the complete result, six segments with no duplicates

Notice the text variable: each round appends a segment, then yield return text. What you output is the whole string, not just the segment you added. This is the part of streaming most often written wrong, and the next section is devoted to it.

The sample pauses 400 milliseconds between segments so you can see it “growing” with the naked eye. In real work that pause comes from the computation itself — reading a line, computing a step, querying a record all take time anyway. Do not add Task.Delay just to “look like it is streaming”; what users want is real progress, not animation.

The code before yield return is “what has to be done before this frame”. Inside the loop it runs once per frame; outside the loop it runs only once (say preparing data, or connecting to the database once). This distinction matters for streaming. Put something that “should happen only once” inside the loop and six frames do it six times, doubling how long the user waits.

The value of streaming is not just “looking fast”. It makes the “waiting” visible. When the user sees the first segment, they know the program is working and that their click was not wasted. Those ten seconds change from “blank” to “segments appearing one after another”, which feels completely different.

One number captures this: time to the first segment. Without streaming, the user waits for “everything to finish”, ten seconds; with streaming, the user waits for “the first segment”, 400 milliseconds in the sample. The total time is not reduced at all, but the time to “a reaction” drops from ten seconds to 0.4 seconds. People judge “is it stuck” by this number, not by the total duration. Chat applications almost all stream, because “the start” comes earlier.

Streaming also has a side effect that is easy to miss. It turns one request into a series of responses. Originally it was one HTTP request and one response; now it is one request and dozens of pushes. The connection has to stay open, and every push along the way can fail. This is why streaming code has one more layer of “what to do when something goes wrong” than an ordinary handler function; Chapter 17 picks this up.

16.2 Output Semantics, Intervals, and Multi-Component Output

Each frame outputs the “current complete value”, not “the part added in this frame”.

What happens if you write it to “output only the increment”? The output component replaces its whole value each time it receives a frame, so if you output “Segment 2”, the screen is left with only “Segment 2”; output “Segment 3” and only “Segment 3” remains. Each frame overwrites the previous one, so the text appears to jump. To have the text keep growing, every frame has to output everything.

This mistake is common because intuitively “streaming” means “sending one segment at a time”. What is sent one segment at a time is the protocol layer (the server writes back one fragment at a time), while the UI layer wants “what the whole text is right now”. Between the two layers there is one accumulation. Join the fragments together, then output the joined whole. The text += delta in the sample’s Ask is exactly this accumulation.

This is where this semantics differs from “appending”. The output component has no “append” operation, only “replace with this value”. Streaming just makes that “replace” happen many times.

If there is more than one output component, each frame has to give a value to every output. For example, streaming text and a counter at the same time: yield return (text, count), matched up in order against the outputs list. Every frame must supply all outputs. Give only some and the rest are taken as “no value”, which shows on the UI as those components flashing empty. To keep an output’s previous frame, use gr.Skip().

The typical use of multi-output streaming is “main result + side information”. The body text grows while a count rises and a status changes beside it. Output all three together every frame and the UI stays in sync; output only the body and let another event update the count, and the two fall out of step. The user sees the text reach the third segment while the count is still at one.

The order has to match too. The order in outputs decides how the return value is split. Return a three-tuple and the first goes to the first output, the second to the second. Get it backwards and nothing throws — the text simply lands in the counter box. This kind of mistake is obvious on the UI, but when debugging you should think “order” first, not “wrong value”.

streamEvery is this section’s second parameter: the minimum number of seconds between two frames. Omit it and every frame is sent; write 0.5 and output produced faster than half a second is not sent to the front end frame by frame. Its purpose is “do not flood the front end”. A handler function that produces a frame every millisecond is too much for the browser to render and for the network to carry; add a lower bound and the frame count falls into a controllable range.

When should you set it? Look at frame density. Text streaming (a model emitting characters) is usually one frame every few tens of milliseconds and needs no attention; streaming where each frame is heavy, like images or audio, must set it. Without it, bandwidth and CPU are spent on “sending frames” and less time is left for the actual computation.

streamEvery is in seconds; 0.5 means half a second. Writing 0 is the same as omitting it — “send every frame”. It affects only the rhythm of “sending”, not the rhythm of “computing”. The handler function still yields as many times as it should; the frames are just sent more sparsely.

It and triggerMode: AlwaysLast solve problems at different layers. streamEvery governs the rhythm of sending: frames are still produced, just not sent one by one. AlwaysLast governs the choice of what to queue: new ones displace old ones, and old frames never even reach the handler function. The former suits “every frame carries information” (text), the latter “only the latest matters” (camera images).

One more point that is easy to forget: streamEvery is a binding-level parameter, not an application-level one. Within the same application a text stream can leave it unset while an image stream sets 0.5, each following its own density. You do not have to slow down every stream for the sake of one heavy one.

There is also an implicit convention: the last frame must be complete. The framework does not know when your business logic is done; it only knows the sequence has ended. The last frame when the sequence ends is the final result. So do not yield an extra “summary” outside the loop unless you really want it to overwrite everything before it.

Exceptions in streaming need thinking through too. If the sequence throws halfway, the UI shows “stopped midway + an error”. It does not automatically go back to empty, nor does it retract content that has already appeared. The user at least sees the part that was computed. To “clear on failure”, record the failure in catch, then after leaving try first yield an empty string and rethrow the exception (you cannot yield inside catch; Section 16.6 covers this restriction); to “keep on failure”, just let it stop there. Both are fine, but you have to have thought about it.

16.3 Progress: Reporting, Step Reporting, and Display

Streaming solves “having something to look at”; progress solves “how much longer”. It produces no content, it only reports a number.

In terms of writing, the handler function gains one parameter.

async Task<string> WithProgress(Progress progress)
{
    for (var i = 1; i <= 6; i++)
    {
        await Task.Delay(350);
        progress.Report(i / 6.0, $"Step {i}: computing a bit");
    }

    return "**Progress** all six steps done, the last frame is the complete result.";
}

Progress is not written into inputs. Parameters injected by the framework do not take up an input slot. Progress, CancellationToken, and event data are all in this category. What if you declare it as an input? The framework will look for a value in a component to fill it and error if it cannot find one; even if it finds one, what you get is not a progress object.

Why must it be injected? Because progress does not belong to any component. It is the state of “this run”, following the call, not the page. If you made it an input component, you would get things like “last round’s progress being read by the next round”; as an injected parameter, every call gets a fresh object belonging only to that run.

This also explains “why you do not place a component on the page for the progress bar”: it is a channel. The handler function writes into it, the front end reads from it. You can write as many times as you like; what is read is always the last one.

Report(fraction, description) takes two parameters: how far along (0 to 1), and a line of text for a person to read. The small label in Figure 16-4 reads “Step 4, computing a bit · 66.7%”. The first half is the description, the second half the percentage the framework computes from fraction.

Figure 16-4 Progress: description plus percentage, following whichever step the handler function has reached

What do you pass for fraction? “The proportion already done.” Six steps with the fourth finished is 4/6 ≈ 0.67. Pass null to mean “progress unknown”. By the contract, no progress bar is drawn then, only the description is kept. Some tasks cannot compute a proportion (say waiting on an external interface); using null is more honest than inventing a number.

Two other methods report “which one / how many in total”, with the fraction computed by the framework itself.

  • ReportSteps(index, total, description, unit): you tell it which one you are on and how many there are in total;
  • Track(values, description). You pass a collection to it and it reports as it iterates; the denominator is the number of elements.

Replace the progress.Report(...) line in the sample and you have these two forms.

    // The total is known: report "which one / how many in total"; the framework computes the fraction.
    progress.ReportSteps(4, 6, "Sub-step 4", unit: "step");

    // A collection to iterate: pass it to Track and it reports as you go.
    foreach (var name in progress.Track(new[] { "Read", "Compute", "Write back" }, "Three segments"))
    {
        await Task.Delay(200);
    }

The unit of ReportSteps is “what one step is called”; if you omit it the unit is steps. Track is less work. You do not count yourself or compute a fraction — just pass the collection to Track. It reports “which element you are on”; when the elements are done it is 100%, and however many items the collection has, that many cells appear on the UI.

Track has a boundary. The tracker stays attached until the collection is exhausted. Nest another Track inside and one push carries two trackers, of which the client shows the later one. The outer one’s progress then stops moving. To nest, use ReportSteps on the outer layer and count yourself.

Update(steps) gets its name from “advance a few steps”, but you cannot see it on the UI. After the call nothing has changed, and the index in later pushes is not affected either. To accumulate, keep a variable yourself and pass it to ReportSteps. One extra variable is better than one more progress bar that does not move.

Which of the three methods to pick? A rule of thumb: when the loop count is known and even, use ReportSteps; when processing a collection, use Track; when progress cannot be computed, use Report(null, "...") and let the description run along without drawing a progress bar.

Where progress is shown is decided by the binding’s showProgress. The sample writes ProgressDisplay.Full, so that small label appears in the top-right of the panel; omit it and you get the default compact style, just a thin line. You can also specify showProgressOn to display progress on a different component — say the progress bar in the status area and the result in the result area.

Can progress and streaming be used together? Yes, but keep them distinct: streaming replaces content, progress reports a number. With both on, the UI has text growing segment by segment and also a progress line — the most comfortable form. The user both sees things coming out and knows how much is left.

There is a detail when using them together. Every streaming frame refreshes the output component, and progress also refreshes that component’s corner badge; the two do not fight (one changes content, the other the badge). But if showProgressOn points to another component, progress is displayed there instead. This parameter is very useful when building a UI that separates “result area + status area”.

There is another common mistake: reporting progress inside a streaming handler function, but reporting “which frame”. Frame count and business progress are often not the same thing — one frame might be one segment of text, or a whole result. Report progress by business steps, not by frame count.

The last point: progress must be real. Report is called by the handler function itself; the framework does not compute it for you. Write a fake timer that advances it at a constant rate and the user will think “that is smooth”, then get fooled once on a step that hangs. After that one time, they never look at the progress bar again.

16.4 Timer and Timed Triggers

Some things are meant to happen when the time comes: polling a status, refreshing a dashboard, fetching data every few seconds. Timer is made for this.

var clock = gr.Timer(2, active: false);

Two parameters: the interval in seconds and whether it starts running immediately. It draws nothing. You cannot see it on the page; what it does is make the front end fire a tick event every two seconds.

tick binds a handler function just like an ordinary event. In the sample look at “start” and “stop” along with it.

    pane.Clock.Tick(OnTick, null, [pane.Tick], apiName: "Timer");

    flow.Start.Click(StartClock, null, [pane.Clock, pane.Tick], apiName: "Start timer");
    flow.Stop.Click(StopClock, null, [pane.Clock, pane.Tick], apiName: "Stop timer");

Three bindings. tick does the work, the other two change “whether to run”. Both buttons treat the timer itself as an output, because what they change is its Active.

The handler function looks like this.

string OnTick()
{
    ticks++;

    return $"**Timer** {ticks} ticks, the latest at {DateTimeOffset.Now:HH:mm:ss}.";
}

Figure 16-5 shows the result of “start → wait six and a half seconds → stop”: the timer panel reads “stopped, 3 ticks in total”. Three ticks is exactly the number those six and a half seconds should produce; after stopping, another four seconds passed and the number did not change.

Figure 16-5 The timer: one tick every two seconds after starting, and no more after stopping

Stopping deserves its own explanation. Write Active back to false, then put the timer into the return value.

(Gradio.Net.Timer, string) StopClock()
{
    pane.Clock.Active = false;

    return (pane.Clock, $"**Timer** stopped, {ticks} ticks in total.");
}

Why return the component itself? Because Active is a property written into the page configuration, and the front end watches it. When the configuration becomes false, the front end clears that clock. Change only the field on the C# object without returning it and the front end never sees the change, so the clock keeps running.

The timer has one boundary that is easy to step into: it runs only while the page is visible. Switch to another tab and the browser stops the timer; switch back and it resumes. This is to save power. But for a requirement like “must sample every two seconds”, it is not reliable enough. That kind of requirement has to be handled on the server (a background task); you cannot count on the front end.

The other side of this boundary is “it does not need the server to remember anything”. The timer is a clock inside the page. The server only writes “every two seconds” and “whether to run” into the configuration; the browser does the rest. So when the page is closed, the clock is gone. There is no such thing as “the server is still counting for you”.

When should you use a timer? Three kinds of scenario: polling (asking “is it done yet” every few seconds), refreshing (numbers on a dashboard updating themselves), and rhythm (automatically switching an image every so often).

tick goes through the queue. With the page open and the timer firing every two seconds, the queue always has events; if the tick handler function is slow, the queue piles up and other people’s requests are blocked outside (Chapter 15). So it has to be light. Read a number, update a piece of text — do not do heavy work inside it.

If you really need heavy work, let tick do only one read. Read a status, a file, or a counter, and continue only if it changed. The essence of polling is “most of the time nothing has changed”; make that “no change” pass light and polling pays off.

Polling is the most common use, and it is written in three steps: the timer fires every two seconds, tick asks “is it done yet” once, and when it is done you stop the timer. The third step is easy to forget. Forget it and the page keeps asking until the user closes the page. So the tick handler function usually has a check. When the work is done, write Active back to false and return the timer — the same set of actions as the stop button at the start of this section.

The timer also interacts with the queue: its tick is queued by default. If the previous tick has not finished when the next one arrives, two ticks sit in the queue, which shows up as “running slower and slower”. To avoid it, bind tick with concurrencyLimit: 1 and triggerMode: AlwaysLast (Chapters 5 and 15). A new tick displaces the old ones that have not run, so only the latest one is ever processed.

16.5 Streaming Input from Media Components

Chapter 11 covered Image’s streaming: true; here we add where it fits into “streaming”.

Turn it on and the camera sends frames to the server one at a time, each frame triggering one stream event. Audio and video work the same way. In other words, streaming for media components is an input stream. Data flows from the browser to the server, and the handler function is called repeatedly.

This is the opposite direction from the streaming in earlier sections of this chapter. An output stream is “one call, many returns”; an input stream is “many calls, one value each”. The two share a word but have completely different code structures.

  • Output stream: one handler function, returns IAsyncEnumerable;
  • Input stream: one handler function, receives one frame, returns once, called many times.

What is an input stream good for? Real-time filters, real-time recognition, transcribing while recording. What is it bad for? Anything that “needs to see the whole segment”. Transcribing a piece of audio or editing a piece of video has to wait until recording is done. The criterion is simple: can this task produce a result from this one frame alone. If yes, use an input stream; if not, wait until recording finishes.

The two are often used together. Take a “transcribe while recording” feature: the audio component has streaming input on, transcribing each small piece as it arrives (input stream), and the resulting text is appended to the panel segment by segment (output stream). With the two streams stacked, what the user sees is “words appearing as they speak”. This is the most elegant use of streaming and also the hardest to tune. The two sides have different rhythms — input fast, output slow — so there has to be buffering in between.

The cost of an input stream is on the queue. One event per frame, thirty frames a second is thirty events. All the limits from Chapter 15 apply here: the concurrency limit decides how many frames are processed at once, the queue limit decides how many pile up. So before turning on an input stream, think clearly about “how long one frame takes to process”; when you cannot keep up, dropping old frames is more sensible than queuing them.

Dropping frames means setting this kind of binding to triggerMode: AlwaysLast. When a new frame arrives, old ones that have not run are displaced. For live images this is right: what the user wants is “now”, not “every frame from three seconds ago”.

One more thing to think through: each frame of streaming input is a complete new value, not an “increment”. What the camera sends is this frame’s image, not “the difference from the previous frame”. So the handler function processes a whole image from scratch every time; there is no “continuing from last time”. To remember state across frames (say “how many times this face has appeared”), use the state from Chapter 14, and watch out for concurrency. When two frames are processed at the same time, the state gets trampled.

16.6 Connecting to an OpenAI-Compatible Service

The previous five sections all made up their own data. This section connects to something real: an OpenAI-compatible service and a real streaming conversation.

Configuration first. The address, key, and model name are not written into the code; they are read from environment variables.

    public static string? Missing
    {
        get
        {
            var missing = new List<string>();

            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_BASE_URL"))) missing.Add("OPENAI_BASE_URL");
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))) missing.Add("OPENAI_API_KEY");
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_MODEL"))) missing.Add("OPENAI_MODEL");

            return missing.Count == 0 ? null : string.Join(", ", missing);
        }
    }

Three variables: OPENAI_BASE_URL (up to and including /v1), OPENAI_API_KEY, and OPENAI_MODEL.

The model name also comes from an environment variable, because the model name is the decision of “which model this deployment uses”; it belongs to the runtime environment, not the code. The same code uses a cheap small model on the development machine and a large one in production — what changes is the environment variable, not the source. This is the same idea as UploadFolder in Chapter 12: environment-related things live in the environment.

When the environment variables are read matters too. The sample reads them on every request, not once at startup into storage. Environment variables cannot be changed after the process starts, so both approaches give the same experience for “changing configuration”: both require a restart. The only difference is a few extra string lookups per request, which is negligible. If you really care about that overhead, store them in a static field and write clearly that “changing configuration requires a restart”.

When configuration is missing, the sample says plainly which items are missing instead of making up an answer.

Figure 16-6 Configuration missing: the panel lists the missing variable names and gives no answer

This is deliberate. A clever-looking answer whose content is made up would cover up “never actually connected” until something fails in a real environment.

For the same reason, the sample does not write the address, key, or model name into any log. Tempted to print them while debugging? Print “configuration complete” and “which item is missing” instead. Once a value has been printed, it stays in some log file on some machine and can never be taken back.

With configuration complete, asking one question is one HTTP request. Here you use await foreach.

async IAsyncEnumerable<string> Ask(string question)
{
    var text = "";

    await foreach (var delta in ChatBook.AskAsync(question))
    {
        text += delta;
        yield return text;
    }

    if (text.Length == 0)
    {
        yield return "**Model** returned no content this time.";
    }
}

What ChatBook.AskAsync produces are fragments (a few characters each); here you append each to text and output the whole text. The division between the two layers is clear. The client handles “produce a fragment as soon as one is read”, the UI layer handles “join it into a complete value”. The “output the complete value every frame” rule from Section 16.2 is put into practice right here.

Why not have the client produce the complete value directly? Because it should not know what the UI wants. The client does one thing: pull the characters out of the SSE one by one. What happens after that (joining into complete text, counting characters, filtering sensitive words) is the caller’s business. That is the value of layering. Switch to a different UI (say the command line) and the client does not have to change.

That if (text.Length == 0) has to stay too. Sometimes the model returns an empty stream (the service is fine but there is not a single character); then await foreach never enters the loop and text is still empty. The UI shows nothing and the user thinks it is stuck. Adding a line “returned no content this time” at least tells them the model said nothing, not that the program broke.

Figure 16-7 is one answer from the real service, to the question “explain in one sentence what streaming output is”; a complete sentence appears in the panel.

Figure 16-7 One answer from a real service, with fragments joined into one complete sentence

A timeout is mandatory. The sample sets 60 seconds on HttpClient; without it, a stuck service leaves the handler function hanging, the queue slot occupied, and every later request waiting in line. 60 seconds is a compromise. A normal answer finishes in a few seconds; one that shows no sign after 60 seconds can safely be declared dead.

Service errors need to be explained too. On a non-2xx response the sample returns a line “the service returned 500, no answer this time” instead of throwing, because throwing inside streaming shows up on the UI as “a red block” the user cannot understand; returning a line at least tells them what happened.

Three kinds of failure have to be reported separately: no configuration (which variables are missing), cannot connect (wrong address, service not started, waited too long), and service rejection (wrong key, model does not exist, rate limited). The user actions for the three are completely different. For the first, set the environment variables; for the second, check whether the service is up; for the third, check the key and quota. Report all of them as “something went wrong” and the user can only try each one in turn.

The first is handled by that Missing check earlier; the other two are caught in code like this.

        // You cannot yield inside a catch, so record the failure first and yield it after the try block.
        string? failure = null;
        HttpResponseMessage? response = null;
        try
        {
            response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
        }
        catch (HttpRequestException)
        {
            failure = "(Could not connect to the service, no answer this time.)";
        }
        catch (TaskCanceledException)
        {
            failure = "(Timed out, no answer this time.)";
        }

There is a C# restriction to know here: yield return cannot be written inside catch (nor inside a try that has a catch). So “catch an exception then output a line” in streaming code needs a workaround. Record the failure in a variable first, then yield after leaving try. This workaround is not pretty, but it is the only way to let the stream keep going.

There is one more case: the connection breaks halfway through reading. The connection is established and headers received, then nothing after some frame. In that case await foreach throws and the sample does not catch it. The UI shows an error and the content already produced stays where it is. This is the same thing as “keep completed results on failure” in Chapter 17, which covers it in detail.

Multi-turn conversation is simple at this layer too. messages is an array and you put history messages into it one by one. The sample puts only one, because this chapter’s conversation is a single question; for multiple turns, convert the ChatMessage list from Chapter 13 into an array of {role, content}. The two structures are almost identical — when converting you only need to drop the blocks and keep the text.

One more thing to know about real services: the answer may contain Markdown. What a model emits is often text with **, lists, and code blocks; a Markdown output component is exactly right for it, while a Textbox shows those symbols literally. The sample uses Markdown, so the sentence in Figure 16-7 is rendered.

16.7 Request Structure, Streaming Fragments, and the End Marker

This section lays the protocol out. Knowing it is what lets you switch to another service or write your own compatibility layer.

The request is a POST to <base>/chat/completions, with Authorization: Bearer <key> in the headers and JSON in the body.

{"model":"<model name>","stream":true,"messages":[{"role":"user","content":"<question>"}]}

This is how it is assembled in code.

        using var request = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/chat/completions");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
        request.Content = new StringContent(
            JsonSerializer.Serialize(new
            {
                model,
                stream = true,
                messages = new[] { new { role = "user", content = question } },
            }),
            Encoding.UTF8,
            "application/json");

stream: true is the key: without it the server computes everything and returns in one shot; with it the server writes back as it computes. messages is an array, each entry with role and content. Multi-turn conversation just means putting a few more entries into this array (the message structure from Chapter 13 becomes the request body here).

There are a few other fields commonly included. temperature controls “how random” (0 most stable, 1 most divergent), max_tokens controls “the most it may generate”, and the system role can carry one overall instruction. The sample includes none of them. What this chapter verifies is “how to wire up the stream”, not “how to tune parameters”. In a real application you will run into these sooner or later.

Only two request headers are required: Authorization and Content-Type. The former carries the key, the latter is application/json. Some services also want Accept: text/event-stream, but that header is of limited use. The response type is decided by stream: true, not by Accept.

Without stream, the response is one whole piece of JSON, with the body text in choices[0].message.content.

{"choices":[{"index":0,"message":{"role":"assistant","content":"Streaming output means..."},"finish_reason":"stop"}],"usage":{"total_tokens":133}}

With stream, message becomes delta, only one segment is given at a time, and the whole response turns into a series of “server-sent events” (SSE). The field names of the two responses differ by one word. message is “one complete item”, delta is “the increment for this segment”. Get it wrong and what you read is always empty.

A streaming response comes back frame by frame as “server-sent events” (SSE); the server never gives one whole piece of JSON at once. Each line looks like this.

data: {"choices":[{"delta":{"content":"Streaming"},"index":0,"finish_reason":null}]}

Taken apart: data: is the prefix, followed by a piece of JSON; choices[0].delta.content is the text of this segment. Some services also include delta.reasoning_content. That is the model’s “thinking”, not the body text; the sample’s parser takes only content, so the thinking is naturally skipped.

A real stream looks like this (most of the middle frames are omitted).

: keepalive

data: {"choices":[{"delta":{"role":"assistant","content":""},"index":0,"finish_reason":null}]}

data: {"choices":[{"delta":{"content":"Streaming"},"index":0,"finish_reason":null}]}

data: {"choices":[{"delta":{"content":"output"},"index":0,"finish_reason":null}]}

data: {"choices":[],"usage":{"prompt_tokens":6,"completion_tokens":127,"total_tokens":133}}

data: [DONE]

The first frame is often “empty”: content is an empty string and there is only role. It is telling you “output has started”. The last two frames have no body text either — one is usage statistics, one is the end marker. Only the ones in between are the actual characters.

There are four kinds of line to recognize in the stream.

  • Blank lines, used as separators, skipped;
  • Lines starting with a colon (say : keepalive), comments the server uses to keep the connection alive, skipped;
  • data: [DONE], the end marker, stop when you read it;
  • A data: whose choices is an empty array. Some services append a usage statistic (token counts) at the end; it has no body text, so skip it.

Only when all four are handled is the parsing complete. Miss one and the symptom is “the stream never ends” or “a strange extra piece of text at the end”.

The finish_reason field has three values: stop for normal completion, length for truncation (hit max_tokens), and content_filter for being blocked by a content policy. The sample does not read it. When the stream ends it simply ends; but to build something like “if the answer was truncated, should we continue generating”, you have to read it.

One more point. The same id appears in every frame of this whole round. It is “the number of this round of conversation”. To pick out “which frames belong to the same request” among a bunch of concurrent streams, it is what you rely on. The sample does not use it, because the sample opens only one stream at a time; with real multi-way concurrency (say two users asking at once), it is the key.

The name delta in a frame is easy to misunderstand. It is called “increment”, and indeed each frame’s delta.content is only “the characters added in this frame”. In other words, the protocol layer is incremental, the UI layer wants a complete value. That accumulation between the two layers is exactly what this chapter has been talking about all along. The name is not wrong; it just describes the protocol, not the UI.

Errors come in two kinds. One is at the HTTP layer: the status code is not 2xx and the response body usually has a {"error": {...}} saying whether the key is wrong, the model does not exist, or it was rate limited. The other is inside the stream: the connection was established and broke midway, in which case await foreach throws. The sample does not catch this one, so the exception goes straight to the UI; to catch it, wrap await foreach in a try and turn it into a line a person can understand.

HTTP-layer error codes should be matched up: 401 is a wrong key, 404 a wrong model name or path, 429 rate limiting (come back later), 500 the service itself failing. These four cover the vast majority of cases; see the code and you know what to change. The sample reports only the code, not the original text, because that text can be long and may carry the server’s internal information.

There is also an “error” that reports no error: empty content is returned. The service ends normally without a single frame of body text, the UI shows nothing, and the user thinks it is broken. The sample checks for exactly this and returns a line “returned no content this time”. In streaming, “empty” and “never ran” look exactly the same, so you need that line to tell them apart.

When writing your own compatibility layer, there is one more rule: each frame must be complete JSON. SSE is split by lines, so a frame cannot span lines (unless you use multi-line data:, which is a different form with poor compatibility). So the server must not serialize with indentation. Indented JSON becomes several lines and falls apart when the client reads line by line. The JsonSerializer.Serialize the sample uses does not indent by default, which is exactly right.

Once you have the response, the first thing is to check the status code.

        using var _ = response!;
        if (!response!.IsSuccessStatusCode)
        {
            yield return $"(The service returned {(int)response.StatusCode}, no answer this time.)";
            yield break;
        }

The first line, using var _ = response!;, arranges for the response object to be disposed. var _ is a placeholder name; when the function ends, that response is released. The try in the previous step only “got the response in hand”; the using here adds “give it back when done”.

The ResponseHeadersRead option: the default is “return only after reading the whole response body”, which would make streaming pointless; with it, the call returns as soon as the headers arrive and the body is processed as it is read.

Reading is done one line at a time. There is a detail here: ReadLineAsync waits until “a complete line exists” before returning. If the server has written a segment but not yet the newline, it keeps waiting. For SSE this is exactly what you want: one frame per line, and a frame counts as arrived only when its line is complete.

        string? line;
        while ((line = await reader.ReadLineAsync(cancellationToken)) is not null)
        {
            // Blank lines and comments starting with a colon (some services send keepalives) are not data.
            if (line.Length == 0 || line.StartsWith(':')) continue;
            if (!line.StartsWith("data:", StringComparison.Ordinal)) continue;

            var payload = line[5..].Trim();
            if (payload == "[DONE]") break;

            var delta = Content(payload);
            if (!string.IsNullOrEmpty(delta)) yield return delta;
        }

Buffering at the network layer helps too. ResponseHeadersRead keeps the response body from being buffered as a whole, and StreamReader buffers only a small chunk. With neither layer accumulating, a frame can be “read as soon as it arrives”. The other way round, if any layer in between reads the whole response body into memory before handing it to you, streaming degrades into “wait for everything, then process”. The code looks unchanged on the surface, but the behavior changes completely.

This piece of code is the whole of what “protocol” means here. Switch to another vendor’s compatible service and, as long as it speaks this format, not a single character has to change; if it does not (say a private protocol of your own), this is the section you change.

The cancellationToken in this snippet is currently an empty token (none is passed at the call site); Chapter 17 will wire it up to real cancellation.

16.8 Chapter Summary

Start with a number. The sample’s “streaming run” has six segments at four hundred milliseconds each, two and a half seconds in total. Return the same content in one shot and the user stares at a blank for two and a half seconds; stream it and the first segment is out after four hundred milliseconds. In those two and a half seconds the user sees six times “it grew a bit more” — that is what streaming buys you.

Streaming is written by returning IAsyncEnumerable, with each frame outputting the current complete value. The output component only “replaces with this value”, it does not append. Output only the increment and the text on the UI jumps; to have it grow continuously, every frame must supply everything. With multiple outputs every frame must supply all of them, and gr.Skip() keeps an output’s previous frame; streamEvery adds a minimum interval between frames so the front end is not flooded.

Progress is an injected parameter and does not take an input slot. Report reports a fraction plus a description; ReportSteps and Track report “which one / how many in total” (Update does not push, do not use it); showProgress decides where it is drawn. Progress must be genuinely reported by the handler function — the framework does not compute it for you.

Timer draws nothing; it only makes the front end fire tick on a schedule. To stop it, write Active to false and return the timer. Only when the configuration changes does the front end stop. It runs only while the page is visible, so do not hang heavy work on it, and polling should stop the clock itself when the work is done.

streaming on media components is an input stream: one call per frame, the opposite direction from multi-output streams. Whether you can use it depends on “can this one frame alone produce a result”.

The real-service part has four things: configuration comes from environment variables, missing items are stated plainly, the request carries stream: true, and the response is read line by line as SSE. After data: is JSON, delta.content is the body text, [DONE] is the end, and lines starting with a colon are comments. After reading, join the fragments into a complete value and output it to the UI.

The chapter’s four things each govern one stretch. Streaming makes content appear segment by segment, progress gives the waiting a scale, the timer makes things happen on their own, and the real integration gives all three something to show.

The next chapter covers “what to do when you do not want to wait”: cancelling a running task, and how failure, timeout, and cancellation should each be presented.

Chapter 17. Cancellation, Errors, and Task Status

After the streaming task from the previous chapter starts running, users have a few new questions: they got the calculation wrong and want to stop — how do they stop it? After stopping, what is that half-finished thing on the screen? And what should the UI say when an error suddenly appears after a long run, and how do you tell “the click did not register” from “it is still queued” when nothing happens after a click?

Cancellation, failure, timeout, and a request being turned back before it ever reaches the handler function all count as “endings that went badly.” The UI has to state honestly what happened: do not call cancellation a failure, and do not call a failure a success.

The example adds a fifteenth block to the workbench, the task module. One long task of twenty steps at half a second each, a cancellation that takes effect immediately, a cancellation that deliberately queues, plus a timeout you build yourself, two different failures, a clear button, and an entry with a validator.

Why twenty steps at half a second each? To make “cancellation” visible. If the task is too short, it is over the moment you click and there is no chance to cancel; if it is too long, readers get impatient. Ten seconds is just right. Click cancel around the third or fourth second and five or six steps remain on screen while the other fourteen never appear. To see which step it stopped at, just count the steps on screen. Every figure below was captured within that duration.

17.1 Cancellation Tokens and Events Waiting in the Queue

The handler function needs one more parameter.

async IAsyncEnumerable<(string, object)> Steps([EnumeratorCancellation] CancellationToken token)
{
    var done = 0;

    try
    {
        for (var i = 1; i <= TaskBoard.Steps; i++)
        {
            await Task.Delay(TaskBoard.StepDelay, token);
            done = i;

            // The step changes on every frame; gr.Skip() holds the result until the last step.
            yield return (TaskBoard.StepText(done), gr.Skip());
        }
    }
    finally
    {
        // Completion, cancellation, and errors all pass through here: record which step it stopped at, and read it out when the panel is cleared.
        TaskBoard.Stopped(done);
    }

    yield return (TaskBoard.StepText(done), TaskBoard.Finished(done));
}

CancellationToken and Progress are the same kind of thing: injected by the framework, taking up no input slot (Chapter 3, Chapter 16). You do not write it into inputs; if you do, the framework will instead go looking inside the components for a value to fill it with. There is no such thing in a component, so you end up with an empty one.

You might think: why not write my own volatile bool _stop, read that flag once per round inside the handler function to decide whether to continue — why use a token at all? It does work for a single call; the problem shows up in three places. First, the same handler function may be called several times at once, and one bool cannot tell which call is which. Second, the stretch of waiting inside await does not return early just because you flipped the bool; it waits as long as it was going to. Third, the framework knows nothing about that bool — it only knows “do we want the next frame?” A token solves all three at once: one per call, it can interrupt the wait, and the framework recognizes it.

The [EnumeratorCancellation] annotation is for async sequences. It lets the compiler wire the token to the enumerator, so that when whoever runs await foreach cancels, the token reaches this method. Ordinary handler functions (the kind that return Task<string>) do not need this annotation; just list the token as a parameter.

A token alone is not enough. With nobody to trip it, it stays “not cancelled” forever. What trips it is cancels on the binding.

    Dependency longRun = job.Run.Click(Steps, null, [work.Steps, work.Result],
        apiName: "Long task", concurrencyId: "Tasks", concurrencyLimit: ConcurrencyLimit.Of(1));
    job.Stop.Click(Cancel, null, [work.Status], apiName: "Cancel", cancels: [longRun], queue: false);
    job.QueuedStop.Click(Cancel, null, [work.Status],
        apiName: "Queued cancel", cancels: [longRun], concurrencyId: "Tasks", concurrencyLimit: ConcurrencyLimit.Of(1));

What cancels accepts is the binding object itself, that is, the return value of Click (a Dependency). Not the button, not apiName, and not the handler function name. So to cancel an event, you first have to store that binding in a variable. That is the entire purpose of the longRun variable in the example.

Once this is written, one more entry shows up in the config. Open /config and look. Besides the ones you wrote yourself, there is an entry with api_name set to unnamed, queue: false, and cancels pointing at the “Long task” binding, attached to the same trigger as the cancel button. The framework adds this one itself, specifically to send cancellation requests. Write several cancels and you get several such entries. The example has two cancel buttons, so there are two.

Click cancel and the frontend sends three requests in total. POST /gradio_api/run/predict runs your own cancellation handler function, POST /gradio_api/cancel carries event_id and fn_index, and finally POST /gradio_api/reset wraps things up. Of the three, the middle one performs the cancellation, and that is what Figure 17-1 draws.

Figure 17-1 The four steps a cancellation takes

cancels may be cancelling “the run that is executing” or “the run that is still queued.” Both are called cancellation, but they mean different things. The running one means “stop here”; the queued one means “this does not need to start at all.”

The latter is cleaner. In the example, click “Run long task” twice. The first starts running, the second goes into the queue (same group, concurrency limit 1). Click cancel now and the second one never enters the handler function from start to finish. It does not even write the “start” line in the log. Since the handler function never ran once, there are no side effects to clean up — much less trouble than “running halfway and then stopping.”

This distinction is easy to miss because the button the user sees is the same one. Click cancel right after starting the task, while it is still waiting in the queue, and what you cancel is “the run that has not started.” Conversely, if three are already queued, one click of cancel clears only one.

What the cancellation request carries is an event_id, not “this handler function.” You cannot see the difference when there is only one user; it shows up as soon as there are several. The same binding may have several runs going at once: two tabs each running one, or two people each running one. What cancels cancels is “this one run” — the framework identifies the caller by event_id and the binding by fn_index. So you do not need any extra design for “several people using it at once,” and you should not expect one cancel click to stop everyone’s runs; it stops only this one.

17.2 How a Running Handler Function Receives a Cancellation

After the token is tripped, the next await throws OperationCanceledException. The example’s await Task.Delay(TaskBoard.StepDelay, token) behaves exactly like this. Cancellation happens between step 5 and step 6; the wait for step 6 throws immediately, the loop ends, and the sequence produces nothing more.

Once it throws, two things happen at the same time. First, the sequence stops producing and the framework stops pulling; second, finally runs as usual. The example makes use of both. finally records “which step it stopped at” and reads it out to the user when the panel is cleared.

yield return cannot go inside catch (the restriction from Chapter 16), but it can go inside try paired with a finally. That combination happens to separate the two concerns. On cancellation you should not emit one more frame anyway, so catch need not produce anything; everything that needs cleaning up goes in finally.

Do not treat cancellation as failure. Cancellation is something the user actively pressed, not a program going wrong. So do not write throw new Error("The task failed") in the cancellation handler. That sentence would make users think they broke something. The example’s cancellation handler says only “Cancellation requested; the steps already produced stay where they are” — all of it factual.

One more thing is easily overlooked. The token has to actually be passed down. Taking the token as a parameter and then calling await Task.Delay(1000) without it is the same as not taking it at all. The user clicks cancel, the program still runs to the end, and the UI finally shows “Done.”

Every frame in the example’s streaming loop carries the token, so after cancellation it stops after at most another half second. Half a second is the length of one step; cancellation takes effect only at “the next await” and does not cut off the half second already being waited out. That granularity is acceptable; if each of your steps takes five seconds, you need to slice finer inside the step, or users will feel “I clicked and nothing happened.”

The three places you usually need to pass it are these. To wait a while, use Task.Delay(duration, token); to send a request, use SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token); to read an async sequence, use await foreach (var item in Source(token).WithCancellation(token)). Miss one place and cancellation breaks there. It stops only at the next wait that carries the token, and the stretch in between is wasted waiting.

What belongs in finally? Things that “must happen however it ends” — release a semaphore, close a connection, flip the “running” flag back to “idle,” record “which step it stopped at.” The example uses the last one because it is useful to the user. Do not throw an exception inside finally. It would mask the real cancellation exception, and what shows up in the UI becomes “an error popped up after cancelling,” which is even harder to explain.

A token will not interrupt synchronous code for you. This is the easiest trap to step on. A for loop doing pure computation with no await will not throw no matter how many times the token is tripped. Cancellation is cooperative; the code itself has to check the cancellation state. In that kind of loop you check manually.

for (var i = 0; i < rows.Count; i++)
{
    token.ThrowIfCancellationRequested();
    total += Heavy(rows[i]);
}

ThrowIfCancellationRequested throws OperationCanceledException — the same one Task.Delay throws — and the outer finally runs just the same.

Timeout and cancellation throw the same exception, OperationCanceledException. So when you see it in the log, do not rush to write “the user cancelled.” It may also be a time limit you set yourself. The way to tell them apart is the when filter in 17.5. Only if the outer token was tripped is it a user cancellation; if it was not, it is the time limit. Writing those two as the same line in the log makes post-mortem debugging take a long detour.

Here is a counterexample. Write the long task’s wait as Thread.Sleep(500) instead of await Task.Delay(500, token). With that, the cancel button does nothing at all. Thread.Sleep ignores the token, and it holds the thread so that even other requests are affected (the “synchronous blocking kills concurrency” point from Chapter 15). Both streaming and cancellation require the handler function to be “awaitable.”

Streaming handler functions and ordinary handler functions differ here. When an ordinary handler function’s token is tripped, the framework gives up at the “waiting for it to return” step; when a streaming handler function’s token is tripped, it gives up at “the next pull.” With the former you can only rely on the token throwing by itself; with the latter, even if you never pass the token, the framework stops asking for another frame after the next yield return. So streaming cancellation looks more “responsive,” but that is only appearance. The steps that should stop inside the handler function still have to stop themselves.

What if an ordinary handler function simply does not take a token? On the surface it looks the same. Click cancel, the UI stops waiting, and the status line reads “Cancellation requested.” But the code on the server is still running. When it finishes, its result is discarded; if it writes a file, that file has already been written. Cancellation means “the UI stopped waiting,” not “the server stopped working” — those two become one only when you pass the token. Every step in the example carries the token, so “stopped waiting” and “stopped working” happen at the same time.

17.3 The Cancel Button That Does Not Queue

The cancel button says queue: false. This is not optional decoration.

The queue is first-in-first-out (Chapter 15). An event goes in and waits for the ones ahead of it to finish before its turn comes. If the cancel button also queued, it would have to line up behind “the very task it wants to cancel.” By the time its turn comes, the task has already finished.

The example puts two cancel buttons side by side precisely to show this. Both are attached to the same long task, both set concurrencyId: "Tasks" with a concurrency limit of 1, and the only difference is queue.

  • “Cancel” has queue: false, does not enter the queue, and takes effect immediately when clicked;
  • “Queued cancel” has none, enters the queue, and lines up with the long task.

Click “Queued cancel” while the task is running and the UI stays so quiet you suspect the click did not register. The status line keeps reading “Standby” while the steps keep growing. It really is waiting. Only when the task finishes is it let through, and then what it does is “cancel a run that has already ended” — it cancels nothing and leaves only a “Cancellation requested” line in the status.

Figure 17-2 Queued cancel: the status still reads “Standby” while the steps have already reached step 6

Switch to “Cancel” with queue: false, click at the same moment, and it stops after at most another half second. The steps stop at whatever step they were on (step 5 in Figure 17-3), and the status reads “Cancellation requested.”

Figure 17-3 The non-queued cancel stops as soon as you click; the steps already produced stay where they are

Look at the two figures together and the difference is not in the button, but in “the moment its turn comes.”

The cancel button also has a handler function of its own (Cancel in the example) that writes just one status line. That line is not optional either. Without it, nothing on the UI changes after you click cancel. Cancellation itself is silent (17.5), so the user has no evidence that “the click registered.” That is why a cancel button almost always needs a line of text, even if it is only “Cancellation requested.”

Incidentally, this handler function is also outside the queue (queue: false along with its binding). If it queued, the “the click registered” line would also appear only after the task finished, which is the same as not writing it.

Let me also clear up an easy source of confusion. “Queued cancel” queues because it and the long task are in the same concurrency group (concurrencyId: "Tasks"). By default each binding forms its own group, in which case “Queued cancel” would run immediately and you would see no difference at all. It would still cancel the same long task, just with nothing blocking it. The example deliberately sets the groups equal to put “queuing” out in the open.

queue: false has a second benefit: it bypasses the queue size limit. Chapter 15 sets maxSize to 2, and new requests are rejected when the queue is full. If “Cancel” were also in the queue, it would be exactly when you need it most that you could not click it. The “Clear panel” button in the example also has queue: false, for the same reason.

The price is that it is not subject to the concurrency limit. A non-queued event starts running immediately, so its handler function must be very light. Cancel, clear, toggle — buttons like these all meet that condition; they change a few lines of text and do no heavy work. Conversely, a handler function that reads a file or computes for ages written with queue: false is like tearing out the queue’s gate: all the limits from Chapter 15 stop working.

One more detail. When a queue: false event errors out, the user still sees an “Error” block, but since it is not in the queue, the queued count in /gradio_api/queue/status does not change because of it. When debugging “I clicked and nothing happened,” this distinction is useful: check first whether it is in the queue.

To find out how many things are waiting at a given moment, there are two places to look. One is the queue: 1/1 badge in the top-right corner of the panel (Chapter 15) — it is right there in the UI, easy to glance at. The other is to ask the endpoint directly, GET /gradio_api/queue/status, where queue_size is the number waiting; you can ask without the UI at all. Use the latter when writing a load-test script or tracking down “who exactly filled the queue.”

Finally, something common in real use. A user starts a task, sees no response, clicks again, then again. Three are now queued. They click cancel, only one is cleared, the UI is still spinning; they think cancellation is broken and keep clicking. To avoid this, make “the click registered” visible immediately. The button becomes “Cancel,” and the status line reads “Queued, position 2.” The example does not do button states, only status text. “Queued, position 2” explains where you are in the wait, but to mark “you can cancel now” in the UI, the button still has to change to “Cancel.”

17.4 Keeping Completed Results and Clearing Incomplete Output

What should the UI look like after cancellation? The example’s answer comes in two halves.

Frames already delivered stay; undelivered ones are not filled in. The steps cell stops at step 5 and stays at step 5. It does not fall back to blank, nor jump to step 6. Cancellation means “do not compute any further.”

The final result cell stays as it is. The reason lies in how the intermediate frames are written. Every frame outputs (step, gr.Skip()), and gr.Skip() means “leave this cell alone”; only when the loop finishes is a real result emitted once. So at cancellation the result cell still reads “no result yet” and has not been polluted by half-finished data.

Figure 17-4 Halfway through: the steps are growing and the result cell still reads “no result yet”

This figure and Figure 17-3 are two moments of the same thing. In the first the steps are still growing, in the second they have stopped; in both, the result cell reads “no result yet.” That contrast is exactly “keep what is completed, never show what is not.”

Why gr.Skip() instead of “output the previous frame’s value once more”? Because there is no such thing as a “previous frame” inside the handler function. All it has is where the computation currently stands. To output it once more you would have to keep your own lastResult — one more variable, one more assignment, and one more overwrite. With gr.Skip() the framework holds that cell down for you, and the function writes only this one word.

With multiple outputs, the position of gr.Skip() has to line up with outputs. The example’s outputs is [work.Steps, work.Result], so the tuple’s first item is the step (changes every frame) and the second is the result (always Skip). Getting them backwards raises no error; it just means that after cancellation the “Result” cell turns into the step text. Chapter 16 covered this point, and here it shows up again.

The steps cell uses Markdown, so **Steps** renders as bold; switch to Textbox and those two asterisks show up literally (Chapter 8). The division of labor between the two panels is set the same way. The steps are explanatory text showing current progress, so use Markdown; the result may need to be copied away later, and Markdown works for that too, but if you want to leave room for copying, switch to Textbox.

gr.Skip() is not only for streaming. When an ordinary handler function returns several values and you only want to change one of them, return gr.Skip() for the rest and the UI will not flicker. Chapter 3 covered gr.Update(); the difference between the two is this. Update means “change to these properties,” Skip means “leave this cell alone.” Use Update to change one cell’s properties, Skip to leave it completely untouched.

“Clear panel” does exactly one thing: reset all three cells together. It is not split into three buttons, “Clear steps,” “Clear result,” “Clear status.” Split it and the user needs three clicks to get back to the start, and the two intermediate states (only the steps cleared) are meaningless in themselves. If one operation can say it all, do not split it into three steps.

The opposite way of writing it is common: write intermediate results into the result cell too (“currently at step 5”). Then after cancellation the user sees “currently at step 5” and can easily take it away as the answer. The result cell holds only the final result; put intermediate states elsewhere — steps, progress, status, any of them.

Cleanup is a separate matter. After cancellation, the half-finished data left on the UI has to be cleared sooner or later, so the example provides “Clear panel” and, along the way, reads out the line recorded in finally: “last stopped at step 5.” That line is both a receipt for the cleanup and evidence that “cancellation really happened.”

That line is stored inside TaskBoard like this.

    /// <summary>Record which step this run stopped at.</summary>
    public static void Stopped(int done) => Volatile.Write(ref _lastStop, done);

    /// <summary>Which step it stopped at last time, told to the user.</summary>
    public static string LastStop
    {
        get
        {
            var done = Volatile.Read(ref _lastStop);
            return done < 0 ? "Not run yet." : $"Last stopped at step {done}.";
        }
    }

One integer, two atomic reads and writes. Cancellation and clearing can happen at the same time (the user clicks fast), so a plain field will not do.

But to be clear: this _lastStop is one number shared by the entire application, not one per session. If one person stops at step 5 and another clicks clear, the second sees “last stopped at step 5” — someone else’s record. The example writes it this way to keep things simple; a real product would put it in session state (Chapter 14), or just keep it in the UI and not carry it across requests.

There is one more detail at the top of the panel. While the task is running, a thin line runs along the top edge of that block. That is the progress bar’s default style. ProgressDisplay.Minimal draws only the line, no text. Chapter 16 used ProgressDisplay.Full, which adds a small “Step N · xx%” label; the third value is Hidden, which draws nothing. Pick among the three levels by occasion. Use Full for a long task meant for people to watch, Minimal when you only want to show “it’s moving,” and Hidden when the handler function reports no progress at all. Keeping a line that reports no number can only say “it’s running” and cannot say “how far along” — you are better off not drawing it.

There is also a question people often forget. After cancellation, if you refresh the page, is that “half-finished” data still there? The answer is no. The panel’s values follow the session (Chapter 14); a refresh is a new session, and everything goes back to its initial value. So “cleanup” actually has two layers: one is the button, for users who do not want to refresh; the other is the session, for users who have refreshed. Do neither and the UI keeps the old data from last time, and users cannot tell this run’s data from the previous one.

17.5 Telling Cancellation, Failure, and Timeout Apart

The three kinds of “did not finish” look completely different in the UI, and this section lays them out.

Cancellation is silent. After clicking cancel there is no toast and no error block; the UI simply stops changing. That is correct. The user pressed it themselves and does not need to be told again. The example adds a line of status text in the cancellation handler as confirmation that “the click registered,” not as an error.

There are two kinds of failure. When the handler function throws an ordinary exception (the example’s “Fail” button), an “Error” block appears in the result area with no toast. That is because the exception message is for developers and should not be pasted straight onto the user’s screen. Throw Error (the example’s “Business error” button) and a toast pops up in the top-right corner with that sentence appearing verbatim; the result area gets an error block too. It shares the same landing spot as an ordinary exception — the only difference is whether that toast is there.

Figure 17-5 Business error: the toast shows the sentence the handler function wrote

Where is the difference? An ordinary exception means “the program hit something it did not expect”; the user cannot follow the details and should only know “this run did not succeed.” Error means “the program expected this, it is a business rule,” and that sentence is written for the user to read.

Timeout you build yourself. The framework sets no execution time limit for ordinary tasks (17.7 covers this), so the example sets its own.

    /// <summary>
    /// Do a piece of work; if it exceeds <paramref name="limit"/>, give up and return false.
    /// When the caller cancels itself (the token is triggered), it does not count as a timeout and is rethrown as-is.
    /// </summary>
    public static async Task<bool> WorkAsync(TimeSpan work, TimeSpan limit, CancellationToken token)
    {
        using var gate = CancellationTokenSource.CreateLinkedTokenSource(token);
        gate.CancelAfter(limit);

        try
        {
            await Task.Delay(work, gate.Token);
            return true;
        }
        catch (OperationCanceledException) when (!token.IsCancellationRequested)
        {
            return false;
        }
    }

Three lines are the key. CreateLinkedTokenSource joins “user cancellation” and “the time limit you set” together; CancelAfter trips it automatically when the time comes; the when after catch separates the two cases. If the outer token was not tripped, the time limit is up; if the outer token was tripped, it is a user cancellation, and in that case you should not say “timeout.”

Once the handler function gets false, it throws a sentence a person can understand.

async Task<string> Timeout(CancellationToken token)
{
    var finished = await TaskBoard.WorkAsync(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(3), token);

    if (!finished)
    {
        throw new Error("Waited too long: still not done after three seconds, so this run is dropped.");
    }

    return "**Result** ten seconds of work finished within three seconds.";
}

Figure 17-6 Timeout: the toast says “waited too long” and an error block appears in the result area

The user’s next action is completely different in the three cases. After cancellation they may want to change a parameter and rerun; after failure they should check the log or find a developer; after timeout they should split the task smaller or come back later. Write all three as “something went wrong” and those three actions become indistinguishable.

There are three more things to watch when writing this. First, do not catch everything with catch (Exception). Catch every exception and you mix “user cancellation” together with “the program crashed.” If you catch, catch something specific: give OperationCanceledException its own catch, and do not catch the rest — let them bubble up to the framework and become an error block, which is where they belong.

Second, the granularity of a timeout equals the granularity of await. When CancelAfter reaches its time it only trips the token; the real interruption happens at the next await. If there is a twenty-second stretch of synchronous computation in between, the timeout does not take effect at the third second either — it takes effect after that stretch finishes. To be precise, slice the long computation into segments and check once between segments.

Third, do not turn a timeout into “pretend it finished”. Return an empty result or half-finished data and the user will take it for the answer. Say plainly that it timed out; better to leave that cell empty.

Should you retry automatically? The answer differs in the three cases. A timeout can be retried once, but loosen the time limit a little or the second run ends the same way; with failure it depends on whether the action is idempotent. Querying data can be retried, charging a payment cannot; cancellation must never be retried — the user has clearly said no, and running it again is the worst experience.

Set the three wordings side by side. Cancellation is “you told it to stop, it stopped at step 5”; failure is “it broke on its own, this run did not succeed”; timeout is “it was too slow, no result came back.” The subject of each sentence is different. Cancellation belongs to the user, failure to this run, timeout to the waiting — and each one says what to do next.

It is also worth logging them separately. Log “cancelled at step N” for cancellation, the exception type and message for failure, and “gave up after N seconds” for timeout. All three carry a start time and the number of steps completed. When you later want to know “how long did that run actually take and where did it stall,” those three numbers are what you rely on. The example writes no log because it puts all three things into the UI; an application that really goes live needs both sides.

17.6 Error and Runtime Notifications

This section has two Errors, so tell them apart first. One is the exception type Gradio.Net.Error: throw it with throw new Error("...") and this run counts as failed. The other is the gr.Error(...) method, which only reports one sentence and lets the run continue. Same name, opposite jobs.

The Error exception is the exit the framework leaves for “the business rules say no.” The timeout and business error in 17.5 both use it.

string Biz() => throw new Error("Not allowed by the business: no new orders this month.");

Once thrown, the UI does two things. An “Error” block appears in the result area, and a toast pops up in the top-right corner with the title Error and that sentence as its body, staying for ten seconds by default. Besides that sentence, the type carries four optional parameters: duration (give it null or 0 and it stays until the user closes it), visible, title, and printException. The last one controls logging. For a “normal rejection” like a form filled in wrong, there is no need to write a stack trace into the log every time, so you can set it to false. Ordinary exceptions take a different route: only an error block, no toast, a generic sentence on the UI, with the details kept on the server (17.5).

The four runtime notification functions are another route.

// Illustration: the example calls only one of these functions
gr.Info("This is a piece of information", 8);
gr.Warning("Watch this step");
gr.Error("There is a problem here, the task continues");
gr.Success("All four notifications sent");

All four functions take two parameters: a sentence, and how many seconds to show it; omit the seconds and it defaults to ten. All four return void. The levels are info, warning, error, and success, and the default titles are simply those capitalized: Info, Warning, Error, Success. The toast picks its icon and color by level: red for error, yellow for warning, green for success, neutral gray for info.

They do not change this run. They do not interrupt the handler function, take up no output slot, and do not change values already on the UI. The example’s “Validate and run” uses one of them.

string Checked(string text)
{
    gr.Success("Validation passed, result updated.");
    return $"**Result** Validation passed, received '{text.Trim()}'.";
}

When the input is ok, click it and the result cell updates as usual while a green success toast appears in the top-right corner at the same time; the toast disappears on its own after ten seconds and the result stays. That is exactly where these functions belong: the work is done, so say a line in passing.

One boundary is easy to trip over. These four functions only recognize “the run that is currently executing.” The framework attaches the notification outlet to the handler function’s call: call them from inside the handler function and the message goes out with that run’s stream; call them during page construction, after startup, or from some other background thread and the outlet is empty — the call is quietly dropped and nothing appears on the UI. So they are neither logging functions nor global notification functions; if you want to send one, send it inside the handler function.

You can see what the message looks like without going through the UI. That gr.Success in the example emits a log message frame like this during the run (Chapter 22 explains how to read this stream).

data: {"msg":"log","event_id":"…","log":"Validation passed, result updated.","level":"success","duration":10,"visible":true,"title":"Success"}

The fields are a contract. log holds the body, level holds the level, title holds the title, and visible and duration control whether it is drawn and for how long. Omit the seconds and duration is 10; write 8 and it is 8. The field names match Python’s LogMessage: when the frontend gets a log message, these are exactly the names it reads, and there is no message field in this frame. Put the body in some other field and the message still goes out, but nothing is drawn on the page. So debugging splits into two steps. If there is no log frame at all, check whether the call landed inside the handler function; if there is a frame but no toast, compare those five fields one by one.

The four toasts are drawn in the top-right corner of the page, stacked, and disappear when their time is up. That “they disappear” is the boundary between them and the status panel. One-off notifications go through toasts; conclusions that need to leave a trace go into the panel. What leaves a trace in the example are those Markdown panels. The “Status” cell records cancellation and clearing, the result cell records validation passed. Cancellation writes “Cancellation requested; the steps already produced stay where they are,” clearing writes “Panel cleared. Last stopped at step 5,” and validation passed writes “Validation passed, received ‘ok’.” All three are short and stay there until the next operation changes them.

So there are four routes for giving the user feedback; pick by whether to interrupt and whether to leave a trace.

  • throw new Error("..."). Interrupts the run, error block plus toast, for “this run did not succeed.”
  • Any exception. Interrupts the run, error block only, for “the program hit something it did not expect.”
  • The four notification functions. No interruption, one-off, for “say a line in passing.”
  • A status panel you write yourself. No interruption, leaves a trace, for “something you still need to see next time you open it.”

There is one rule for writing notification text: a single sentence needs two things — what happened, and what to do next. “Something went wrong” gives only the first; “Waited too long. Still not done after three seconds, so this run is dropped” gives both. The toast floats in the top-right corner, covering what the user is looking at, so the body should be no more than a line and a half; if you really need three lines, that is the status panel’s job. Keep the log and the UI separate too. The log holds stack traces, parameters, and timestamps; the UI holds only one sentence and one way out — do not stuff debugging information into a toast.

17.7 Binding-Level Validation and Execution Time Limits

Some requests should never reach the handler function at all: empty input, wrong format, no permission. Letting the handler function check itself works too, but by then it has already “entered the handler function.” It took up a concurrency slot and ran once before discovering it should have been turned back at the door.

A concrete example. An “Import spreadsheet” button, clicked when the user has not selected a file. The handler function’s first line checks “the file is empty, return immediately,” which looks fine, but it has already gone into the queue and taken a slot. A few hundred misclicks a day and these empty runs are queue slots wasted for nothing.

validator is what turns people back at the door. It is an optional parameter on the binding, a delegate by type; the example writes it as Func<string, string?>.

    job.CheckRun.Click(Checked, [job.Check], [work.Result], apiName: "Validate and run", validator: (Func<string, string?>)Validate);
string? Validate(string text) =>
    text.Trim() == "ok" ? null : throw new Error($"Only ok is accepted here, but got '{text.Trim()}'.");

Parameters are injected in the order of inputs, the same contract as handling (Chapter 3). Put one Textbox in inputs and the validator accepts one string; framework-injected parameters like Progress, CancellationToken, and Request can also appear in the validator’s signature. Return null to let it through; return any other string or throw an exception and it is a rejection.

Rejection happens before queuing, so the handler function never runs once, no concurrency slot is taken, and that queue spot is freed immediately. When the queue is full, a batch of bad requests will not shut out the good ones. The endpoint puts the reason in detail. Returning a string gives 422, throwing an exception gives 400; the example takes the latter. On the page the result cell does not change by a single character, the top-right corner states the reason, and the result area is marked “Error” (Figure 17-7).

Figure 17-7 The validator rejects: the result area does not change by a single character and the top-right corner explains why

Returning a string and throwing an exception both reject. The only difference is the status code: returning a string gives 422, throwing gives 400. The example uses throw new Error(...), taking the 400 route; change the validator to text.Trim() == "ok" ? null : "Only ok is accepted here" and it blocks the request just as well, and that sentence on the page is still perfectly readable.

The validator and the checks inside the handler function divide the work differently. What you can decide up front goes in the validator; what you only know after running goes in the handler function. Whether the input is empty, whether it is ok — the validator answers in a second; “whether this file actually has any data” needs opening it first, and that is the handler function’s job. The validator also sees only the values in inputs. To check “does this person have permission” or “is this file still there,” get permission from an injected service (Chapter 21) and check the file’s existence yourself.

Do not do heavy work in the validator. It sits on the request path and runs on every click; query a database or read a large file and the user first feels “I clicked and nothing happened” before seeing the rejection. If you really must query, cache the result in state (Chapter 14). Validate on the frontend too. The frontend layer is “telling you the format is wrong as you type” — fast, with no server resources. The validator layer blocks requests that bypass the UI and go through /call (Chapter 22). Write both: the frontend for experience, the validator for correctness.

One more boundary: the validator is attached to the queue entrance. The direct /run call from Chapter 22 does not go through the queue, so it does not pass the validator either. Call /run/Validate and run directly with bad and the handler function runs as usual and hands back its result as usual. To block every entrance, the check still has to stay in the handler function.

timeLimit is another optional parameter on the binding, typed double?, and null if you omit it. The name tempts you into reading too much into it. It is not “how many seconds this run may take at most,” and not “how many seconds it may wait in the queue at most.” What it governs is the kind of run where the browser feeds the server frame by frame. As Chapter 16 explained, when a media component has streaming: true, the browser sends each frame to /stream/<event_id> and the handler function runs once along with it.

Remember the boundary in three parts.

  • Ordinary tasks are not covered. Add timeLimit: 3 to the example’s “Long task” and try it: that streaming task of twenty steps at half a second each still runs for ten seconds and hands back its result normally. The ten-second task is advanced frame by frame by the queue itself; the client has nothing to send, so there is no clock to watch.
  • Queue waiting is not covered. A request sitting in the queue is not rejected for waiting too long; the limit only affects this run’s budget and sets no countdown for people in the queue.
  • Input-stream runs go by budget. The first call’s duration is recorded as first_iteration, and the time for each later frame wait plus rerun is added to run_time; once the total reaches the limit, generation stops after the current frame is produced. Intermediate frames send process_streaming; with a nonzero limit, the frame carries a time_limit whose value is the limit minus the first call’s duration. The timeout while waiting for the next frame is computed as “limit minus the first call’s duration”; with no limit it starts at 30 seconds, and writing timeLimit: 0 also falls back to 30 seconds; when the first call uses up the entire budget, there is no more waiting. The output stream that the queue advances itself still sends process_generating, with no time_limit.

The corresponding field written into /config is time_limit, and its value is exactly the number you gave the binding. The easiest way to confirm the boundary is to add a very small limit to an ordinary task and see whether it still runs; then try a binding with an input stream. The parameter having a place in the signature and a place in the config, and which segment it actually governs, are two different things.

So the execution time limit for ordinary tasks still has to be built yourself — that is the WorkAsync from 17.5, CancelAfter plus one Error, within twenty lines. When writing it, keep two things separate: the limit has to be told apart from user cancellation (that when filter), and after a timeout you have to give a sentence a person can understand.

Look at validation and the time limit together and they are two halves of the same idea. Validation governs “should this start,” the input-stream budget governs “should this continue.” Both are decided outside the handler function, so the handler function only has to do the work; but an ordinary task’s “should this continue” has no ready-made budget, so that part is still your own job.

17.8 Chapter Summary

The four “endings that went badly” each have their own wording in the UI.

Cancellation rests on two things. The handler function takes an injected CancellationToken, and the binding says cancels: [that binding]. The token has to be passed all the way down — carry it into Task.Delay, SendAsync, and await foreach for cancellation to work; in a synchronous loop you call ThrowIfCancellationRequested yourself, because the token will not interrupt it for you.

The cancel button needs queue: false. A queued cancel waits until the task finishes before its turn comes, and by then there is nothing left to cancel. The same reasoning applies to buttons like clear and toggle; the price is that they are outside the concurrency limit, so their handler functions must be very light.

Split the output into two cells. What is completed goes into the result cell; what is not goes into steps, progress, or status; intermediate frames use gr.Skip() to hold the result cell down. That way after cancellation the user sees “how far it got,” not “a half-finished answer.” Cleanup has two layers too: the button clears once, and refreshing the page clears again.

The three endings must be describable separately. Cancellation is silent, both kinds of failure give an error block (the business error adds a toast on top), and the timeout you build yourself with CancelAfter plus a sentence a person can understand. Write all of them as “something went wrong” and the user has no idea what to do.

The validator stands at the door. What you can decide on the request path does not belong in the handler function. It takes no concurrency slot and changes nothing on the UI. The /run that skips the queue does not pass through it, so when every entrance has to be blocked, the check still needs a copy inside the handler function.

timeLimit governs only input-stream runs. Ordinary tasks and queue waiting are both outside it; the execution time limit for ordinary tasks you build yourself with CancelAfter.

To “let the user see,” there are four routes: the four runtime notification functions like gr.Info, the toast (throw new Error), the error block (any exception), and a status panel you write yourself. One-off notifications use the toast and those four functions; conclusions that need to leave a trace go into the panel.

The token lets the task stop, queue: false lets cancel actually be clicked, the two-cell output makes what stopping looks like clear, and the three wordings let the user know what to do next.

The next chapter changes direction and splits this page into several pages. Dozens of panels stacked on one page take several screens to scroll to the bottom, and finding a button means first remembering which block it is in. That is already “cannot find it.”

Chapter 18. Advanced Layout and Multi-Page Navigation

The previous chapter’s UI had fifteen blocks: text cleanup, segments, filtering, display, tables, charts, galleries, images, media, files, chat, state, queues, streaming, and tasks. Scrolling to the bottom takes several screens, and finding a button means first remembering which block it is in. No functionality is missing, but “cannot find it” is itself already a defect.

This chapter fixes it. Tabs, accordions, and the sidebar tuck things away on the same page; what cannot be tucked away gets split into several pages, each with its own address, reached through the navbar.

The order matters. Tuck away what you can first; split only what you cannot. Tucking away is free — the user stays on the same page and the address does not change; splitting pages has a price. Referencing components across pages gets awkward, the navbar has to be written once on every page, and users may bookmark the wrong page. So this chapter explains how to tuck away first, then how to split.

The example is still that workbench, but the page structure has changed. One page becomes seven, and the seventh is the layout page, set up specifically to put the four containers side by side for comparison. Not a single module was deleted; they were just reassigned to new positions.

18.1 Tabs and Tab Selection Switching

Tabs cut a region into several screens. Only one is drawn at a time, and a row of buttons beside it switches screens.

Tabs tabs;
using (tabs = gr.Tabs(selected: "one"))
{
    using (gr.Tab("Overview", id: "one"))
    {
        using (gr.Group())
        {
            gr.Markdown("**Overview** three lines of one result, joined into a block with `Group`.");
            gr.Textbox(label: "Body", lines: 2, interactive: false);
            gr.Textbox(label: "Statistics", lines: 1, interactive: false);
            gr.Textbox(label: "Notice", lines: 1, interactive: false);
        }
    }

    using (gr.Tab("Details", id: "two")) { gr.Markdown("**Details** Switching tabs changes only this block."); }
    using (gr.Tab("Notes", id: "three")) { gr.Markdown("**Notes** Switch away and back, the values are still there."); }
}

tabs.Select((SelectData data) => $"**Tab** Selected '{data.Value}', number {data.Index + 1}.", [], [tabNote]);

Tabs is a container, Tab is its child element, and you put other things inside a Tab. The syntax is exactly the same as Row/Column: using opens a level and the braces close it. The indentation tells you everything, and the layout tree in /config is read the same way.

selected only recognizes the Tab’s id. Give a tab a short id and write that id in selected; omit selected and it defaults to the first screen.

So either give every tab a short id and have selected use it, or do not write selected. The example writes selected: "one" because the first tab’s id is "one". When the UI comes up empty, check this first.

There are two selection events, Select and Change. Both fire; the difference is the payload. Select gives you a SelectData, Change gives you nothing. SelectData has three fields: Value is this tab’s label text (in the example, “Overview”), Index is the position counted from 0, and Selected is a flag. So to ask “which one did the user pick,” use Select; do not count on Change.

When both are bound, whichever arrives last decides what gets written. The example binds only Select, precisely so Change cannot overwrite the line that carries data. Binding both is not wrong either, you just have to accept “the last line wins.” When debugging and the status stops at the Change line, do not assume Select never ran.

Figure 18-1 Switching tabs replaces the whole content block; the status line reads “Selected ‘Overview’, number 1”

What does switching screens cost? Two things.

First, the screen you switch away from is unmounted. The components inside an unselected tab are not on the page; inspect the DOM and you find they are simply not there, not hidden. Switching back draws them again, but the values are still there, because values live in the server-side session (Chapter 14), not in the DOM. The three boxes on the example’s first screen are read-only, so you cannot see this; switch to editable input boxes, switch away and back, and the text you just typed is still there. This is easy to misread. See no such box in the DOM and you assume the value is lost.

Second, the address does not change. Switching tabs sends no request to the router and does not change the address bar. So “this page is complex, separate it with tabs” solves the scrolling problem, not the problem of “sending a link that points at that screen.” For the latter you need one page per screen (18.5), or a deep link (18.7).

What happens when the tabs do not fit? overflowBehavior handles that, with two values.

  • menu (default). What does not fit is tucked into the ⋯ on the right; click it for a dropdown;
  • wrap. What does not fit wraps to a second row and the tab bar grows taller.

Figure 18-2 The viewport narrowed to 780 pixels: on the left it tucks into ⋯, on the right it wraps to a second row

The same set of seven tabs, menu on the left and wrap on the right. When the window is wide the two look identical; only narrowing reveals the difference. menu saves space at the price of half the tabs being invisible — the user does not know there are “Files” and “Chat” screens. wrap shows everything at the price of the tab bar taking two rows and pushing content down. Weighing the two harms, with five tabs or fewer either works; beyond five, if you need the user to see them all, wrap is safer.

This comparison also shows one thing. The number of tabs is a design decision, not an implementation detail. Stuff seven tabs into one page and no matter how they overflow, the user has to read through all the tab names before knowing where to go. At the scale of seven, the more likely answer is that the page should be split (18.5), not that you should change overflow strategy. The example keeps them on one page only so both overflow behaviors can be compared in a single figure.

How do you decide to use tabs? Only when both conditions hold. The blocks are parallel (none depends on any other), and they do not need to be seen at the same time (the user cares about one at a time). For two blocks that need side-by-side comparison, use Row to split them left and right, not tabs — people cannot remember the numbers from the previous screen.

Another easy confusion: a tab is not a radio button. Radio (Chapter 7) selects a value, and that value goes into inputs and is read by the handler function; a tab selects a screen of content, goes into no inputs at all, and only decides which block is drawn. So use Radio for “let the user pick a format,” and tabs for “let the user switch among three views.” Using the wrong one still runs, it is just semantically off. Make format selection a tab and the user will think picking it takes effect, when in fact they still have to click a button.

18.2 Accordion and Sidebar Expand and Collapse

Tabs tuck away horizontally, accordions tuck away vertically. One title, one click, and the content collapses or expands.

Accordion rules;
using (rules = gr.Accordion("Wrapping rules", open: true))
{
    gr.Markdown("Wrap by character count, not by words; strip trailing whitespace and drop blank lines.");
}

Accordion events;
using (events = gr.Accordion("Event conventions", open: false))
{
    gr.Markdown("The order of `inputs` in a binding decides the parameter order; the order of `outputs` decides where each return value goes.");
}

rules.Expand(() => "**Fold** 'Wrapping rules' expanded.", null, [foldNote]);
rules.Collapse(() => "**Fold** 'Wrapping rules' collapsed.", null, [foldNote]);
events.Expand(() => "**Fold** 'Event conventions' expanded.", null, [foldNote]);
events.Collapse(() => "**Fold** 'Event conventions' collapsed.", null, [foldNote]);

Three parameters control the appearance. label is the text on the title, open decides whether it is expanded when opened, and height/maxHeight set how tall the content area can get. The default is open: true, so to “have it collapsed by default” you must write false explicitly. That is what the example’s second accordion does.

There are two events, Expand and Collapse, and both carry no payload. Note that. The handler function’s signature is “no parameters,” not “receives an object saying which one it was.” To know which one was clicked you have to bind them one by one. The example uses four lambdas, each with the name written in directly. Two accordions means four bindings — sounds clumsy, but it is more reliable than guessing which one it was at runtime.

One substantial difference between accordions and tabs: collapsed content is still in the DOM, just not displayed. Tabs unmount, accordions hide. So collapse an input box inside an accordion and expand it again, and the value is right there, not even redrawn. Conversely, components inside an accordion still take up session state and can still be referenced by events. Hiding a “not needed for now” block inside an accordion is a clean way to tuck it away.

The sidebar is the third kind. It is not in the main text flow but clings to one side of the page, collapsed by default, with an arrow left at the page edge.

Sidebar side;
using (side = gr.Sidebar(label: "How to use this page", open: false, width: 260, position: "right"))
{
    gr.Markdown("### How to use this page");
    gr.Markdown("""
        1. Click a tab to switch screens;
        2. Click an accordion title to expand or collapse it;
        3. Click the arrow on the right edge of the page to bring up these instructions.
        """);
    gr.Button("Button in the sidebar");
    var sideNote = gr.Markdown("**Sidebar** has not been opened yet.");

    side.Expand(() => "**Sidebar** opened.", null, [sideNote]);
    side.Collapse(() => "**Sidebar** collapsed.", null, [sideNote]);
}

label is its name, but it is not displayed on the page. It is only there for the code and the config. All the user sees is that arrow. width is the panel width (260 pixels in the example), and position is left or right. The example puts it on the right, because there is already a column of content on the left and the sidebar would cover it.

An expanded sidebar covers the main text, which is different from an accordion. An accordion pushes the content below it down; the sidebar floats on top. So the sidebar suits things you “open to consult at any time and put away when done”: usage instructions, a table of contents, filter criteria. Do not put must-see content in it — users will forget it is there.

One practical point. The sidebar width is given in pixels, 260 in the example. On a narrow screen that is not a small number. A phone is a little over eight hundred pixels wide, so a 260-pixel sidebar takes up a third of it. Keep sidebar content short: three to five lines of instructions, a set of links, one button — do not stuff a table in there. If you need a table, it is not “auxiliary content” anymore and deserves a proper place on the page.

Figure 18-3 “Event conventions” expanded and the sidebar open; both status lines were written by events

All three containers are called “folding” in one way or another, but each covers a different scenario. There are three criteria.

ContainerWhat it holdsWhen to use itCost
TabsSeveral parallel screens of contentSee one at a time, blocks are peersSwitching unmounts components, address unchanged
AccordionSegments within the same pageSegments have an order, you may view two at onceContent stays on the page, just not displayed
SidebarAuxiliary content outside the main textInstructions, contents, filters — things called up at any timeFloats over the main text and covers content

Choosing among the three is not a matter of taste; ask in this order. Is this content on the same level as the main text? On the same level and mutually exclusive, use tabs; on the same level but to be seen together, use Row. Is it part of the main text? Then use an accordion, divided by section. Is it not part of the main text at all? Then it is a sidebar.

Here is a counterexample: collapsing something you “must see.” The example’s accordions hold rule explanations and event conventions — the kind of thing you read carefully the first time and look back at occasionally afterward. That is exactly what folding suits. But fold the “Result” away and the user clicks a button, sees nothing, and has to click a title open as well — that turns folding into an obstacle. Results, errors, and current status should never be inside an accordion; what you may fold are instructions, options, history, and secondary settings.

The height and maxHeight parameters control the content area’s height; the example does not use them because they have to be tuned to the content length. When content exceeds maxHeight, the accordion scrolls internally instead of growing taller. For a block holding twenty lines of log, maxHeight: 240 fits better than letting it grow to a full screen. But it also brings a hidden risk: there is more content below and you cannot see it at a glance. For “must read to the end” things like logs, better to let it grow taller.

An accordion has one more detail that is the opposite of tabs: at page load it all exists at once. Two accordions both open means two blocks of content drawn together, just separated by their titles. So folding does not save server work, only vertical space. If you really want “compute only one block at a time,” that is a tab’s job.

18.3 Group Parameters and Nesting

Chapter 4 covered how to use Group. It joins several child elements into one block with a shared outer frame and no gaps in between. This section adds two things: its parameters, and its place among containers.

gr.Group() has six optional parameters: visible, elemId, elemClasses, render, key, and preservedByKey. In the config the parameter names are written in snake case (elem_id, elem_classes, and so on), and /config’s props keeps only the fields that are used. What the example’s Group writes in is visible: true, empty elem_classes and preserved_by_key, plus a name: "group". The example passes not a single parameter.

using (gr.Group())
{
    gr.Markdown("**Overview** three lines of one result, joined into a block with `Group`.");
    gr.Textbox(label: "Body", value: "The wrapped body goes here.", lines: 2, interactive: false);
    gr.Textbox(label: "Statistics", value: "Six lines, 128 characters, longest line 20 characters.", lines: 1, interactive: false);
    gr.Textbox(label: "Notice", value: "No blank lines and no overlong lines.", lines: 1, interactive: false);
}

You cannot leave out the using level. When the factory creates the Group it also makes it the current rendering scope; only when that scope ends do the components inside get attached in the right place. This also explains why Group and Row/Column are not peers. Those two set direction, while Group decides “whether this counts as one thing”; it has no scale or minWidth of its own, and how wide it is comes from the layer outside it (Chapter 4).

Of the six, the first three are used most. visible controls whether the whole block is drawn. When hidden it does not appear on the page, but the block still stays in the config; elemId and elemClasses leave hooks for stylesheets, and Chapter 19 uses them to land custom CSS on one specific block. The remaining three relate to the component tree and re-rendering, and the example never passes them. Most of the time Group is simply a container whose parameters you do not need to tune.

Group carries no value of its own and emits no signal; in the component tree it is just a node. It does not change the ownership of the components inside it and cannot be used as an input or output. Being placeable at any level is its other trait — inside tabs, accordions, or the sidebar, all fine. The example’s “Overview” tab uses it to hold three lines of results, and the task panel in Chapter 17 uses it to join steps, result, and status into one block.

Nesting works too, but keep it in check. Put a Row inside a Group, a Column inside that Row, and after three levels each level draws its own frame: three nested rectangles on the page, with no telling which edge belongs to which. The rule of thumb is one Group level plus one direction container; beyond that, split it into two modules.

18.4 Step-by-Step Guidance with Walkthrough

The containers in the previous sections do not restrict where the user can click; Walkthrough is the opposite — you can only go forward.

Walkthrough walk;
using (walk = gr.Walkthrough(selected: 0))
{
    using (gr.Step("Preparation", id: 0))
    {
        gr.Markdown("**Step 1** First see how tabs switch screens, then click an accordion title.");
        var next = gr.Button("Next", variant: "primary");
        next.Click(() => GoStep(1), null, [walk], apiName: "Go to step 2");
    }

    using (gr.Step("Processing", id: 1))
    {
        gr.Markdown("**Step 2** Open the instructions in the sidebar, then come back.");
        var next = gr.Button("Next", variant: "primary");
        next.Click(() => GoStep(2), null, [walk], apiName: "Go to step 3");
    }

    using (gr.Step("Wrap up", id: 2))
    {
        gr.Markdown("**Step 3** Done. Switch to the 'Data' page to see tabs used in a real UI.");
        var again = gr.Button("Back to step 1");
        again.Click(() => GoStep(0), null, [walk], apiName: "Back to step 1");
    }
}

// Switching steps means writing the target step number into an Update and passing it to Walkthrough.
static Update GoStep(int step) => new() { Selected = step };

Walkthrough looks a lot like Tabs: both “draw one screen at a time” and both have selected. But three differences affect how you use it.

selected recognizes the Step’s id, not its ordinal. This is the same idea as Tabs recognizing id, but the consequence here is more direct. If a Step has no id, whatever you write in selected comes up empty. If the example dropped id: 0, not one screen of the three steps would show.

Only the current step is drawn. Reach step two and step one’s content is removed from the page. That is the exact opposite of an accordion: folding hides, a walkthrough replaces.

Steps you have not reached cannot be clicked. The dots for steps two and three are gray and the buttons carry disabled, so the user cannot get in. Steps you have passed get a check mark and are no longer gray. So the “order” is locked at the control level.

You write the step change yourself. Walkthrough has no “Next” button of its own. That is where it differs from a typical wizard component. The example puts an ordinary button in each step; after a click the handler function returns new Update { Selected = 1 }, the outputs names this Walkthrough, and the framework changes the step accordingly.

Why design it that way? Because “whether you may go to the next step” usually needs checking. Form not filled in, file not selected, validation not passed — you should not let the user through then. Since the handler function performs the step change, it gets a chance to block it. If validation fails, return an error and leave Selected unchanged. If the framework shipped its own “Next,” that check would have to be crammed in somewhere else.

There are two events, with a division of labor somewhat different from tabs; let me take them separately.

  • Change fires when the step number changes, with no payload. When the program advances via Update, this is the one that fires;
  • Select fires only when the user clicks a completed step, carrying a SelectData whose Value is that step’s title and whose Index is the position counted from 0. After the click it goes back to that step and the content block is swapped back.

The case where both fire is “the user clicks back”: first Select (with data), then Change (without). So to know “which step the user went back to,” bind Select; to know only “the step number changed,” bind Change. The example logs the two events separately. One line writes “changed a step,” the other writes “clicked back to ‘Preparation’, number 1.” Logging them separately keeps the later one from overwriting the earlier one.

One more thing. Clicking the current step fires nothing. No change means no event; do not take it as evidence that “the user clicked but nothing moved.”

Figure 18-4 Step two: step one has a check mark, step three is still gray, and the content is swapped to step two

When should you use Walkthrough? One condition only: the order is rigid and a later step depends on the result of an earlier one. Installing configuration, importing data, first-time setup — all fit. Conversely, use tabs when “the user may look at any block in any order,” and an accordion when “the user decides what to do first.”

18.5 Splitting a Single Page into Multiple Pages

The four containers above solve “one page is too long.” They do not solve a different case: the things on this page should not be together.

Three questions decide “should it be split,” asked in order.

  1. Which blocks are used in one session? If two are never used together, they should not share a page;
  2. Do they share the same input? If they do, keep them on the same page; if not, separate them;
  3. Do you need an address you can send on its own? If so, you must split — tabs cannot produce an address.

Question 1 splits the fifteen blocks into six groups in the example: Text, Data, Media, Chat, Run, Layout. Then question 2 reveals one adjustment. Data and its four views below it share the “item source,” so the item source and filtering stay outside the tabs and the four views go into tabs. Skip this question and after splitting you find “the chart page cannot get the filter results.”

Figure 18-5 No modules lost, more addresses: the home page stays at the root and the other six pages each take a suffix

The split itself is small: four steps.

One, group them on paper first, without writing code. Copy the fifteen block names, connect the ones “used together,” and a closed loop of connections is one group. Get this step wrong and everything after has to be redone — and it costs nothing.

Two, give each group an address segment. Short, English, and showing its purpose: text, data, media, chat, ops, layout. Do not use page1, page2. The address shows up in users’ bookmarks; it has to stand up to being looked at.

Three, fold each group’s “build components + bind events” into one method. This is mechanical work, but there is a rule: the method and the components it uses must be in the same scope. Do not think “declare the components outside so two methods can share them.”

Four, open the pages in order at the root, writing the navbar at the top of each (18.6).

using (demo)
{
    // The home page is the content at the root: it is not written into any page, and its address is /.
    Home();

    using (demo.Route("Text", "text")) { TextPage(); }
    using (demo.Route("Data", "data")) { DataPage(); }
    using (demo.Route("Media", "media")) { MediaPage(); }
    using (demo.Route("Chat", "chat")) { ChatPage(); }
    using (demo.Route("Run", "ops")) { OpsPage(); }
    using (demo.Route("Layout", "layout")) { LayoutPage(); }
}

Except for moving the small “Sharing” block from the end of the page to below the result, the code inside every page method was carried over verbatim. BuildInput(), BuildResult(), and the bindings like arrange.Then(...) were not changed by a single line. That is the payoff of Chapter 4’s “write regions as methods”: when splitting pages you move method calls, not hundreds of lines of component code.

One thing cannot be moved: you cannot reference components across pages. Events can only bind components on the same page, and outputs can only name components on the same page. The old cross-module wiring like “the filter button also updates the display panel” breaks after the split. The example handles it by keeping them on one page (the Data page’s filter and four views), or by letting each mind its own business.

So splitting is not free. For every cross-page dependency, either merge two pages or turn the dependency into an “in-page” one — pass the value through state, or have the user click again. Thinking this through before splitting is less trouble than figuring it out afterward.

Do not call it done right after splitting; run through this checklist.

  • Open each page. Visit every page once, looking for blank pages and errors;
  • Type the address directly. Try the kind of address from a bookmark first, not by clicking in from the home page;
  • Refresh. Press F5 on page two and still be on page two;
  • Cross-page dependencies. Are those “click A changes B” wires still connected? Repair the broken ones;
  • Navbar. It is at the top of every page, the current page is highlighted correctly, and clicking “Home” returns to the root.

Of these five, missing the fourth raises no error. That button does nothing when clicked — exactly the same symptom as “forgot to bind the event” — but for a completely different reason.

The Data page is a real example of “tabs holding modules.”

Figure 18-6 The Data page: item source and filtering above, four tabs below holding display, table, chart, and gallery

This page uses two containers in different positions. The tabs hold “the four views” because they are parallel, mutually exclusive, and need not be seen together; filtering stays outside the tabs because all four views read its result. Choose the wrong position and the code tells you first: a variable goes out of scope and you cannot reach it.

The home page looks like this.

Figure 18-7 The home page: one navbar and six entries with addresses

The home page holds no modules, just one line of explanation and a list. That is deliberate. After the split, the home page’s job changes from “the UI where work happens” to “telling you where the work happens.” If the home page still piles up modules, it is as if you never split at all.

18.6 Routing and the Navbar

demo.Route(...) means “open a page.” It returns something Dispose-able; close the using and that page ends, with the following components back at the root (or in the next page).

Three parameters: name, path, and showInNavbar.

path is the address suffix; text becomes /text. If you omit path, the framework derives one from name — but it only accepts letters and digits, so a name with spaces or non-ASCII characters derives no usable suffix and throws immediately.

System.ArgumentException: The route 'Text' derives no URL suffix;
give it a name of letters and digits, or pass the path explicitly.

The message is clear enough. That is why the example pairs a display name with a short ASCII path: the name is for the user to see, the path for the address bar. The two need not match, and you should not force them to. Non-ASCII paths get escaped by all sorts of tools when copied and pasted; short ASCII words are safer.

path has a few hard rules; break any one and it throws on the spot.

What you writeResult
A route the app owns, like config or gradio_apiRejected — the app already occupies that address segment
Spaces or slashes (my page, a/b)Rejected — a suffix may contain only letters, digits, and -._~!$&'()*+,;=:@[]
A duplicate of an earlier page (both written as text)No error — the later page is quietly renamed to _text

The third does not raise an error. Two pages with the same name are not stopped; at startup the later page is hung on _text, still reachable but not at the address you wrote. The link in the navbar still says text, so clicking it always shows the earlier page. That is where “I clearly clicked page two” comes from. When you find “clicking leads to a different page,” first count whether Route has a duplicate path.

The navbar is another thing to make clear: two facts, one line of code.

// The navbar lists every page automatically (the home page is named with mainPageName), so you do not list them yourself.
// It is a component: it appears only on the page where it is written, so every page has to write it once at the top.
void Top() => gr.Navbar(mainPageName: "Home");

First fact: it lists all the pages by itself. Every page with showInNavbar set to true enters the bar in declaration order, the home page is named with mainPageName, and the current page is highlighted automatically. Tried with a small three-page example. Put only one NavbarLink("Text", "text") in value, and the bar still shows four entries: Home, Text, Data, Media. The links in value are appended, not a “whitelist.” So you do not need to assemble a page list yourself, and doing so would not make it more complete.

Second fact: it is a component, not a property of the page. It appears only on the page where it is written. That is why the example calls Top() once at the top of every page. What if you write it only on the home page? The home page has the bar, clicking into /text loses it, and the user cannot get back. That is not a defect; it matches the component model — components belong to pages, and so does the navbar.

NavbarLink is therefore used in only two cases: adding an external link (write an absolute address as the second parameter), or making one page appear in the bar under a different name. The example adds none, and all six pages are there automatically. Adding an external link works: new NavbarLink("Docs", "https://www.gradio.app") appears in the bar and clicking it jumps straight out. A local-machine app does not need this, but an app delivered to others often wants one.

The third parameter, showInNavbar, decides whether this page goes into the navbar. A page written with false still has its address and can still be opened by address, it just is not in the bar. The example omits this parameter, so all six pages use the default true and all appear. When do you turn it off? Two cases. One is a debug or temporary page you do not want users clicking by mistake; the other is a page “entered from somewhere else,” whose entry point is a button rather than the navigation. This has nothing to do with permissions. It is simply not listed in the navbar — anyone who knows the address can still open it, so do not treat it as access control (Chapter 20).

A page having its own address means three things hold at once.

  • Open /data directly and land on the Data page without going through the home page first;
  • Refresh and still be on the Data page, not back at the home page;
  • Bookmark it, send the link, paste it into a document — all point at this page.

The difference between multiple pages and tabs rests on these three things. Tabs are view switching under one address; multiple pages give each view its own address. When a user wants to “send the chart page to a colleague,” only multiple pages can do it.

After splitting, there is one more place to verify that “the pages really are separate”: open /config and /config?page=text and compare. The former is the whole application’s config, with every page’s components listed; the latter lists only this page’s components and bindings. If some event is missing from /config?page=text, it was bound on another page — exactly the mistake splitting leaves behind. Checking the config pins down ownership directly. In code you have to trace through the using nesting; in the config it is a flat list of ids.

Multiple pages solve “send an address to a certain page,” but not “after sending it, the content matches what is here.” A colleague opens /text and sees their own empty input.

gr.DeepLinkButton() fills this gap. It draws as a button, and one click does three things: ask the server for a token, append the token to the address, and copy the whole address to the clipboard.

gr.Markdown("### Sharing");
gr.Markdown("Click the button below and a `deep_link` segment appears in the address bar; when the copied link opens in a new window, the input box still holds these same characters.");
gr.DeepLinkButton("Copy link with state");

The first parameter is the text on the button; the second, copiedValue, is the text temporarily swapped in after a successful copy. The example writes “Copied”; omit it and the default Link Copied! is used. It lights up for a little over a second, then switches back to the original line. Checking it takes a quick hand — look right after clicking; wait three seconds and you only see the restored version.

After the click, it goes through a very short chain.

  1. The frontend requests GET /gradio_api/deep_link?session_hash=… with the session id;
  2. The server takes a snapshot of the component values recorded for this session and gives that snapshot a short token (the example gets RVKOw2ohFG8, eleven characters);
  3. The frontend appends ?deep_link=RVKOw2ohFG8 to the current address and copies it to the clipboard.

Figure 18-8 The token is only eleven characters; it points at that snapshot in the server’s memory

When someone else opens this link, the server first finds the snapshot by token, fills the component values back in, and then renders the page. What opens is a new session (a new session id), but the page shows the old session’s values. That is what “the ‘Source text’ in the two browser frames in Figure 18-8 is identical” means.

Two things need telling apart here: the session id and the token. The session id identifies this page; it changes on every refresh and the server recognizes the user by it. It is not in the address and the user never sees it. The token is the short segment in the deep link, pointing at “a snapshot of a certain session at a certain moment.” One session can issue many tokens (one per share click), each pointing at the snapshot from its own moment; conversely, a token only goes back to its own snapshot and does not follow later changes to the session.

Put another way, the session id is a house number and the token is a photograph. The house number points to who lives there now; the photograph freezes the moment it was taken.

Figure 18-9 The Text page before sharing: source text, cleaned result, and statistics are all in the session

Testing turned up four things, noted one by one.

First, the token is a reference, not the content. Eleven characters cannot hold several paragraphs of main text; it only says “go fetch snapshot number so-and-so from the server.” So the link is valid only on the same server, within the same process run. Change the port or restart once and the token points at nothing.

Second, an invalid token raises no error and falls back to defaults. Change deep_link to random characters and the page opens as usual with the input boxes at their initial values — the same as having no parameter. That is better than popping up “link expired”; the user can at least still use the page.

Third, the token is a snapshot from the moment it was created. Share first to get token A, then change the input and share again to get token B; opening with A still shows the old values. It is “the photograph from back then.” To get the latest content, you have to click share again.

Fourth, if the last write-back is a property, the value cannot come along. This one is counterintuitive and is often misread as “the deep link is broken.”

The example’s “Source text” box has a Change bound to it (the character count from Chapter 5). While the user types it changes the label to “Source text (23 characters)” and returns gr.Update() with a new label — no value. So after that run, what the server records for this box is a “label-only” property update. Click share then, and the link opens on a box whose label is right but whose value is empty.

Click “Clean up” once and then share, and source text, body, and statistics are all there. What is the difference? “Clean up” reads the source text once as an input and writes the body and statistics back, so the last write carries values.

So the correct statement is this: the link carries away “what the server remembers for this session,” not “what the UI currently shows.” Every run records an entry for the components it used — reads are recorded as values, writes as what was written. But if the last write-back is an Update that only changes properties, that value gets pushed aside by this update. This is the normal result of “a property update overwriting a value.”

The way to judge is plain: before sharing, let the button that actually does the work run once; do not stop at the “only changed the label” step.

One word on security too. The token is a reference: whoever gets the link can see that snapshot. In the example it is the wrapped body, nothing sensitive; swap in a piece of configuration carrying a secret and you should not use this button. Deep links suit “sharing the result of one operation,” not “sharing data in an account.”

One more usage note. Deep links are for people, not for programs. To “pass state between programs,” reading the /gradio_api/... endpoints is more reliable than assembling links (Chapter 22). Links are for people to copy and paste. /text?deep_link=RVKOw2ohFG8 is easier to recognize than a long string of JSON, and the /text in the link plainly marks which page it is.

18.8 Chapter Summary

Tuck away what you can first; split only what you cannot.

Tucking away on the same page, the three containers divide the work clearly. Tabs hold “several screens that are parallel and mutually exclusive,” unmounting components on a switch while values stay in the session; accordions hold “segments within the same page,” where collapsing only hides them and the content remains; the sidebar holds “auxiliary content outside the main text,” floating on the page and callable at any time. The order of judgment: on the same level as the main text → tabs or Row; part of the main text → accordion; not part of the main text at all → sidebar.

All three folding containers have events, but only Tabs.Select carries a payload (Value is the tab’s label text, Index counts from 0). Accordion and Sidebar’s Expand/Collapse take no parameters; to know which one it was, bind them one by one.

selected recognizes id, not text. Tabs and step-by-step guidance are the same; getting it wrong raises no error, it just shows no screen at all. Walkthrough has three more traits: it draws only the current step (not cumulative); step changes must be returned by the handler function as Update { Selected = n }; and it has no “Next” button of its own. Its events come in two kinds: Change covers “the step number changed,” and Select covers only “the user clicked back to a step” (with title and ordinal).

Splitting pages is decided by three questions: which blocks are used in one session, whether they share the same input, and whether you need an address you can send on its own. After splitting, each page has its own address and direct opening, refresh, and bookmarking all work; the price is that cross-page component references do not work and events can only bind components on the same page.

Routing uses demo.Route(name, path, showInNavbar), and the content at the root is the home page. A name that is not plain ASCII letters must be given a path; path cannot occupy a route the app owns, cannot contain spaces or slashes, and cannot duplicate another page (a duplicate raises no error, the later page is renamed to _text) — that one you can only catch by counting.

The navbar is a component and must be written once on every page; it lists all pages by itself (the home page named with mainPageName, the current page highlighted), and NavbarLink is only for appending external links or giving a page a different name.

Deep links use gr.DeepLinkButton(); one click gets a token, appends it to the address, and copies it. The token is eleven characters and points at a snapshot in the server’s memory; an invalid token falls back to defaults; the snapshot is from the moment of creation, not live; and it is valid only on the same server. Last, this one: the link carries what the server remembers, not what the UI shows. If the last write only changed properties, the value carried over is empty.

Finally: if you can tuck it away, do not split; once split, stop thinking about cross-page references; if you want to share, share the result of one run, not “the text being typed.”

The next chapter changes direction: with the UI structure settled, the next step is making it look good. Themes, colors, fonts, custom stylesheets — all work that “changes appearance without changing structure.”

Chapter 19. Themes and Appearance

The first eighteen chapters built up the UI structure and the interactions: seven pages, a dozen or so containers, and over a hundred bindings. They still look like Gradio’s default. A light gray background, orange-red buttons, six-pixel corners.

This chapter’s tools run from coarse to fine: the theme (pick a built-in one, adjust a few shared parameters, then change a few variables), the stylesheet, and head injection; plus binding-level frontend scripts, which are not about appearance — they change “what this one click submits”.

What the four layers share is that none of them touch the structure. The components inside using and the handler functions in the bindings need not change by a single line. If changing appearance really required changing business code, that means styling has leaked into the structure.

The example is still that workbench, with an eighth page, “Appearance”, added to put every tool on the same page; there is also a separate theme experiment project, where the same set of components is photographed once under each of several themes for comparison.

19.1 Choosing a Built-in Theme

A theme is an object; assign it to Blocks.Theme and it takes effect.

var demo = gr.Blocks(title: "Personal Local Workbench");
demo.Theme = new SoftTheme();

That is the whole line. The buttons, input boxes, sliders, accordions, and tab bar on the page all change together. They all read from the same set of CSS variables, and a theme is one set of values for that batch of variables.

The built-in themes have twelve names: base, default, ember, glass, monochrome, neon, soft, origin, citrus, ocean, mario, cyberpunk. There are two ways to get one, and they are equivalent.

demo.Theme = new SoftTheme();              // a typed class
demo.Theme = ThemePresets.Get("soft");     // look it up by name

ThemePresets.BuiltInNames is the list of those twelve names. A misspelled name does not silently fall back to the default — Get throws an exception. That is easier to track down than “waiting until the page has rendered only to find nothing changed”.

What does a theme actually do? Open /theme.css to see. This address returns the current theme’s stylesheet, which holds over three hundred CSS custom properties.

--primary-500: #6366f1;
--neutral-50: #f9fafb;
--spacing-md: 6px;
--radius-lg: 8px;
--text-md: 14px;
--body-background-fill: var(--background-fill-primary);
--color-accent: var(--primary-500);

Every component on the page reads from this batch of variables. A button’s background is --button-primary-background-fill, which points to --primary-500; an input box’s corner radius is --input-radius, which points to --radius-lg. Changing the theme means changing the values of this batch of variables; the components themselves are unaffected.

Figure 19-1 The default theme

Figure 19-2 Soft: the same components, looser letter spacing, larger corners

Figure 19-3 Glass: translucent panels, a background leaning cool

Figure 19-4 Monochrome: the primary color recedes to grayscale, leaving only tonal layers

Figure 19-5 Ocean: blue-green primary color

The components are identical in all five figures: a text box, a slider, a checkbox, a group of radio buttons, two buttons, and one accordion. The differences are entirely in color, text size, spacing, and corner radius.

How do you choose? Two practical considerations.

First, projection and printing. Glass’s translucent layers often blur into a smear on a projector, while Monochrome shows the clearest tonal layers when printed. Choose the former for a presentation people watch, the latter for figures in a document people read.

Second, how much it fights the content. The more saturated the primary color, the more the UI grabs attention and the further the main text recedes. The workbench’s main text is what the user wrote, so the theme should step back; low-saturation primaries like soft and ocean fit better. neon and cyberpunk suit demo pages and event pages, not a tool you stare at for long stretches.

One more thing to be clear about. A theme changes appearance only, not behavior. The button is still that button, the click is still that click. So you can change the theme at the very last moment of development without affecting any binding. But the reverse holds too. A theme cannot rescue a UI with a muddled structure: if two columns are crammed together, ten themes later they are still crammed.

Component properties and the theme are two separate layers. The variant in gr.Button("Clean up", variant: "primary") chooses “which step from the theme to use” — the primary-color step or the secondary step; it does not name a color. So the same line of code is indigo under SoftTheme, dark gray under Monochrome, and blue-green under Ocean. That is also why changing the theme needs no change to component code. The code only says “this is a primary button”; the theme decides the color.

There is only one moment to assign it: demo.Theme = ... has to be written before Launch. Chapter 4 explained that the page is sealed on the first request; changing the theme after that seal has no effect. It raises no error, the page simply keeps the old set. The example puts it at the very top, alongside Queue and the upload directory settings, precisely so that the order “configure first, build the UI next, launch last” is visible in the code.

In /config the theme leaves only a name, a theme_hash, and four body_css rules (the light and dark pairs of the page background and main-text color); the actual three-hundred-plus variables live in /theme.css. The benefit of the split is that the browser can cache the stylesheet. If the theme has not changed, the hash does not change, and the stylesheet need not be downloaded again.

Changing a theme is something people look at, so acceptance is by looking too. Same page, same viewport, content unchanged, only the theme swapped, three shots in a row. If in any one of the three a button is hard to read or a block of text is crammed together, that theme cannot be used. No need to compare parameters one by one; let your eyes go over it first.

There is one rule for taking comparison shots. Viewport, content, and zoom all stay fixed; only the theme changes. Change the viewport and column widths and line wrapping change, so the two shots cannot be compared; change the content (one more line of text, one more accordion opened) and the height changes, again no comparison. The example’s eight theme comparison shots are all 1440×700, the same content, the same set of components.

A theme should appear only once in the code. The example puts it at the top of Program.cs, in the three lines before using (demo): construct, Set, assign. Do not write it again in every page method. Blocks has only one Theme; write it in two places and the later one overwrites the earlier one, while someone reading the code assumes both take effect.

What design hands you is usually a set of concrete numbers: “primary color #7c3aed, corner radius 8 pixels, main text 14 pixels”. Landing it takes three steps. Find the closest hue (the 500 step of violet happens to be #8b5cf6, close but not exact), pick the step (radius_lg), and make up the remaining difference with Set. The order of the three steps cannot be reversed. Picking the hue first and then patching the color is less work than Set-ing a pile of colors first and only then discovering the hue is wrong.

19.2 Theme Tuning Parameters

A built-in theme is not necessarily exactly right. When it is off by a little, you do not have to build one from scratch; just change a few parameters.

var skin = new SoftTheme(
    primaryHue: Colors.Find("violet"),
    radiusSize: Sizes.Find("radius_lg"));

BaseTheme and its eleven subclasses all accept the same set of parameters, eight in all (of the twelve built-in names, base is the base class itself).

ParameterAcceptsVariables changedChange in the UI
primaryHuea hue--primary-50 through --primary-950primary buttons, links, sliders, selected state, focus ring
secondaryHuea hue--secondary-*secondary emphasis (selection highlight on some components)
neutralHuea hue--neutral-*page background, borders, main-text color
textSizea text size step--text-xxs through --text-xxltext in the main body, labels, and buttons
spacingSizea spacing step--spacing-xxs through --spacing-xxlpadding, gaps between components
radiusSizea corner-radius step--radius-xxs through --radius-xxlcorner radius of input boxes, buttons, and blocks
fonta font list--fonttypeface of the main text and headings
fontMonoa font list--font-monomonospaced typeface in Code

Hues and sizes do not accept strings; they accept the objects returned by Colors.Find(...) and Sizes.Find(...). Names use lowercase with underscores: Colors.Find("violet"), Sizes.Find("radius_lg"). Write "Violet" or "RadiusLg" and you get null; then the parameter is null, the theme is still built, and only that one path falls back to the default. No error is raised — unlike a misspelled name in Get("soft").

Here is what “expanding into a color scale” concretely looks like. Give it a hue and the theme generates eleven levels, --primary-50 through --primary-950, from very light to very dark. Each component takes what it needs. A button at rest uses 500, on hover 600, when pressed 700, and a light background uses 50. So what you give is one hue, and what lands is eleven levels; changing the hue swaps all eleven together, and every “shade of the primary color” in the UI follows at once.

Text size, spacing, and corner radius work the same way, with seven levels: xxs, xs, sm, md, lg, xl, xxl. textSize gives the “baseline”, and the theme derives the whole scale proportionally; the difference between Sizes.Find("text_lg") and Sizes.Find("text_md") is “the baseline of the whole text scale raised one step”, so the main text, labels, and button text all change together.

Parameters are a starting point, not a contract. The same primaryHue looks different under different built-in themes. Soft’s buttons are solid fills, Glass’s are translucent. So a request like “change it to ocean’s blue” has to settle the theme at the same time. Pick a base first (Soft, Glass, Monochrome), then tune parameters on top of it; do it the other way — tune parameters, then swap the base — and the earlier tuning is wasted.

secondaryHue and neutralHue are often confused. The difference is in what they are for. neutral decides the base (page background, borders, the color of main-text letters; change it and the whole UI’s light/dark and warm/cool balance shifts; secondary decides the second emphasis) used when some components need a contrasting color besides the primary. When in doubt, change only primaryHue and neutralHue first — those two decide nine tenths of the look.

Colors holds about twenty colors (slate, gray, red, orange, amber, green, teal, sky, blue, indigo, violet, pink, …), and Sizes holds three groups: radius_*, spacing_*, text_*. A hue expands into an eleven-level color scale once it comes in; a text size expands into seven levels. So what you pass is a “hue” and a “step”, not a concrete color value.

Figure 19-6 Only radiusSize, spacingSize, and textSize changed: the buttons turned into capsules, line spacing widened, and the text grew one size

Figure 19-7 Only primaryHue and neutralHue changed: buttons, sliders, and the selected radio change color together, and the background goes from cool gray to warm gray

Viewed side by side, the two figures show the division of labor among the tuning parameters. In Figure 19-6 the colors did not move, only sizes did; in Figure 19-7 the sizes did not move, only colors did. The eight parameters each own one segment and do not cross into the others. That is the difference between “tuning parameters” and “variable overrides”. The former changes a whole color scale at once; the latter changes a single point.

font accepts a list of Font, of three types: GoogleFont, LocalFont, and Font.

new SoftTheme(font: [new LocalFont("Source Han Sans SC"), new Font("system-ui")]);

The three font types land differently; one try is enough to tell them apart.

  • LocalFont("Source Han Sans SC") generates an @font-face whose src points to static/fonts/SourceHanSansSC/SourceHanSansSC-Regular.woff2. You have to place the file into the static directory at that path yourself; otherwise loading fails and it falls back to the next font in the list.
  • GoogleFont("Inter") only writes the name into --font ('Inter', 'system-ui'); it generates no @font-face and has no address pointing at Google, so the font has to be one already installed on the system.
  • Font("Georgia") likewise writes only the name and uses a system font.

The fonts shipped with the built-in themes take the first path. Soft’s stylesheet has an @font-face pointing to static/fonts/Montserrat/...; the file comes with the package and /static/fonts/... serves it directly. So “changing the font” means either putting the font file into the static directory and pointing LocalFont at it, or accepting a system font.

The fonts shipped with the built-in themes are local files. Soft uses Montserrat and IBM Plex Mono; the stylesheet points an @font-face at static/fonts/..., fetched on demand as the page loads. The most visible difference before and after changing the font is character width. For the same main text, Montserrat is a little wider than the system sans-serif, so a line holds fewer characters and the line count goes up. So after changing the font, check line wrapping and height again, especially for text boxes with a fixed number of lines (ones like lines: 2); a wider font can bring on a scrollbar.

Tuning parameters has an order. Settle the hue first (it decides the character), then text size and spacing (they decide the density), and corner radius last (it decides hard versus soft). Changing the hue means re-checking the most components, so settling it first saves going back and forth.

How do you verify after changing? Three actions.

One, print a few values: skin.GetValue("primary_500"), GetValue("radius_lg"), GetValue("spacing_md") — confirm you got the step you thought you did. When a parameter is passed null, the original value shows up here, which is faster than staring at the button on the page and guessing.

Two, compare screenshots. Same page, same viewport, only the theme swapped, the two shots side by side. That is how the example’s two sets of screenshots were made. Not a single component changed; only the BOOK_THEME environment variable was swapped.

Three, narrow the window and look again. Once spacing and text size grow, the stacking point set by minWidth arrives earlier. In the “480 + 320 + 16” example from Chapter 4, the columns stack when the available width drops below 816; enlarge the spacing and the width actually needed is larger, so the two side-by-side columns stack sooner. On a wide desktop screen you see no problem; only on a narrow screen do you find two columns have become one.

19.3 Overriding Theme Variables

Tuning parameters change “a whole color scale” or “a whole step of sizes”. Sometimes the difference is a single point. The primary color one step lighter is exactly right, but changing primaryHue moves the whole scale; an eight-pixel corner radius is exactly right, but radiusSize has only a few steps.

Then change a single variable directly.

var skin = new SoftTheme(primaryHue: Colors.Find("violet"), radiusSize: Sizes.Find("radius_lg"));
skin.Set("primary_500", "#7c3aed");
demo.Theme = skin;

Set takes two string parameters, a variable name and a value, returns the theme itself, and can be chained. A variable name is the CSS variable name with the two leading hyphens removed and hyphens replaced by underscores: --primary-500 becomes primary_500, and --radius-lg becomes radius_lg.

A mistake throws on the spot; it does not silently do nothing.

System.ArgumentException: '--primary-500' is not a theme variable.
The theme has 325 of them, all of which ThemeOptions declares. (Parameter 'variable')

The “start with --” spelling shown in the message is not accepted, and that is the most common source of this error. The same theme has over three hundred variables, and --primary-500 is one of them, yet Set wants primary_500.

Three naming rules.

In CSSIn SetNote
--primary-500primary_500drop --, hyphens to underscores
--radius-lgradius_lgsame as above
--button-primary-background-fillbutton_primary_background_filllong names follow the same rule

Levels in a name are joined with underscores, not dots and not hyphens.

You can also use Css to write a :root { --primary-500: … } block for the same effect, but that is “adding another layer on the outside”. The stylesheet the theme generates still holds the old value, and your override has to guarantee its own priority. Set changes it at the source. What comes out of /theme.css is the new value, and every component that references it follows along. Where both can be changed, prefer Set.

Whether an override took effect can be seen in two places. One is GetValue; the other is fetching /theme.css directly and searching it for the value you wrote. Find it and the stylesheet the server generated already holds the new value; fail to find it and it was not written in (a misspelled name, or overwritten by a later Set).

To know the current value of one variable path, use GetValue.

Console.WriteLine(skin.GetValue("primary_500"));   // #7c3aed
Console.WriteLine(skin.GetValue("radius_lg"));     // 8px

It prints the value exactly as it is, including indirect references like var(--...). GetValue does no resolving. To turn an indirect reference into a concrete value, use GetComputedValue.

Besides Set one variable at a time, there is a strongly typed path, ThemeOptions.

demo.Theme = ThemePresets.Get("default").Set(new ThemeOptions
{
    ColorAccent = "#0f766e",
    RadiusLg = "2px",
});

Every property of ThemeOptions maps to one variable, which suits “change a batch at once and want the property names checked at compile time”. It and Set("name", value) change the same batch of variables; the only difference is the notation, one by string, the other by property.

Figure 19-8 Default theme + primary_500 changed to dark green + radius_lg changed to 2px: only two points changed

This figure and Figure 19-1 use the same components and the same theme, differing by only two variables. Notice where the change lands. The buttons and slider turned dark green, and the corners of the input boxes and buttons went from round to sharp; text size, spacing, and layout did not move anywhere.

There is a side effect here that the screenshot cannot show. Change one step and the others stay old. The example’s override sample changes primary_500 to dark green, so the button is dark green at rest; move the mouse over it and the color becomes primary_600, which is still the default theme’s orange. The rest and hover states no longer match, and the button looks broken.

Measured values: at rest rgb(15, 118, 110), on hover rgb(234, 88, 12).

So single-point overrides have two uses, each with a cost.

  • Change the hue (primaryHue) recomputes all eleven levels, with the light/dark relationships built in, at the cost of changing the whole scale;
  • Change one step (Set("primary_500", ...)) moves a single point, at the cost of having to fill in the neighboring steps yourself.

If you really want a single-point override, change the commonly used steps together: primary_500 for rest, primary_600 for hover, primary_700 for pressed, primary_50 for a light background. Write the four lines together so someone reading the code can tell “this swaps the primary color for another set”.

Single-point overrides suit variables that have no neighboring steps needing to follow. radius_lg, spacing_md, embed_radius, body_text_size — changing one changes all of it.

Order. Construct the theme first (with tuning parameters), then Set the variables. Writing it the other way raises no error either, but the tuning parameters recompute the color scale and overwrite the values you Set earlier. Read in code it is one line after another; in reality it is “set the big direction first, then turn the small screws”.

A finished theme can be saved.

skin.Dump("skin.json");                    // save a copy, with all variables
var same = Theme.Load("skin.json");        // read it back, values identical

Dump writes the current values of those three-hundred-plus variables, and Load reads them back into a complete theme object, names and values intact. It suits two cases: the theme has to travel with the project into version control, or you let a design colleague edit a JSON file while the code only has to read it.

Saving as JSON has one more use. The difference between two themes can be diffed directly. Whatever Set changed shows up as those few extra lines in the file.

ThemeOptions or Set? For a batch of changes where you want property names checked by the compiler, use ThemeOptions; for just one or two points, or when the variable names were copied from elsewhere (a JSON from design, /theme.css), use Set. The two can be mixed. The example’s main app fixes the hue and corner radius with constructor parameters first, then Sets one primary_500. Watch the order when mixing: constructor parameters are computed first, Set writes later, and the later write wins.

19.4 Custom Stylesheets and Head Injection

The theme governs “that batch of variables”. Changes that variable overrides cannot reach (adding a vertical line to one block, turning one line of small text all-uppercase) have to be written in CSS.

There are two places to write it, inline and in a file.

demo.CssPaths = [Path.Combine(AppContext.BaseDirectory, "assets", "skin.css")];
demo.Css = """
    .card { border-left: 6px solid var(--primary-500); padding-left: 14px !important; }
    .badge { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--primary-600); }
    """;

CssPaths accepts a set of file paths, read in when the config is fetched; Css accepts a string. The two are concatenated in the end into the css field of /config, which the frontend injects into the page. So the following two things both hold.

  • The order is “inline first, file second”; for rules with the same name the later one wins, that is, the file’s version wins;
  • When writing the file you need not worry about how the path is delivered. It does not go through the static file service; it is read into memory and joined into the string.

CSS is global: write button { ... } and you hit every button on the page. To change just one spot, you first have to give that spot a hook. Two hooks are given when the component is constructed.

gr.Markdown("# Appearance", elemId: "hero-title");            // becomes id="hero-title"
using (gr.Column(elemClasses: "card")) { ... }          // becomes class="card"

elemId is a unique id, and elemClasses can hold several classes (separated by spaces). Give class names a prefix (the example uses card and badge); do not use ones like button, input, or prose. When they collide with class names the framework or theme ships, the range you hit grows larger than you expect. Both work on containers and on components. gr.Column(elemClasses: "card") hits the whole column, gr.Markdown(..., elemClasses: "badge") hits that one segment. The example’s assets/skin.css relies on exactly these two hooks.

.card { border-left: 6px solid var(--primary-500); padding-left: 14px !important; }
.badge { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--primary-600); }

Figure 19-9 The “Appearance” page: the vertical line on the left of the card and that line of all-uppercase small text are both done by skin.css

Notice the buttons and input boxes inside the card. Their background, corner radius, and text size come from the theme; the vertical line and the small text come from the stylesheet. The two are managed separately, so changing the theme does not touch the stylesheet, and changing the stylesheet does not touch the theme.

There are three practical lessons when writing CSS.

First, prefer variable values, do not hard-code colors. border-left: 6px solid var(--primary-500) follows the theme when it changes color; writing #7c3aed nails it down. Theme variables live on :root and can be referenced anywhere in the stylesheet.

Second, use !important sparingly. The one padding-left: 14px !important in the example is there because the component’s own rule is more specific and cannot be overridden without it. If a more specific selector can win the priority, do not add !important. Add one and the next override can only add another, until the page is full of exclamation marks. The usual way to raise priority is to stack a selector: .card .prose { ... } is more specific than .prose { ... }.

Third, do not forget printing. Dark backgrounds, gradients, and shadows on screen often print as a solid black blob. If you really need printing, add a block to skin.css.

@media print {
  body { background: #fff !important; }
  button, .card { box-shadow: none !important; }
}

The example does not include this block, because the example does not print. Whether to write it depends on whether the app will be “printed to PDF and sent out”.

Files in CssPaths do not go through the static file service. The page makes no request for skin.css; its content is read on the server and joined into the css field of config. That one fact decides three things. The file can live at any path, with no need to move it into a publicly served directory; it is read as plain text, with no HTTP caching; and every config fetch re-reads it, so after editing the file a page refresh shows the change with no restart.

Beyond the stylesheet there is one more place, Head.

demo.Head = """
    <style>
      #hero-title {
        font-family: "Songti SC", "SimSun", Georgia, serif;
        letter-spacing: 0.06em;
        display: inline-block;
        padding-bottom: 4px;
        border-bottom: 2px solid var(--primary-500);
      }
    </style>
    <meta name="book-chapter" content="19" />
    """;

Head accepts a piece of HTML that goes into <head> verbatim. What it adds over Css is not just styles: <meta>, <link>, <script>, and <base> can all go in. The example puts in two, a <style> block and a <meta> tag.

Figure 19-10 The Songti typeface and that bottom border come from the <style> in Head; the <meta> is not displayed but did go into <head>

The division of labor among the three can be remembered like this.

WhereWhat it isScopeWhat to put there
Theme variablesCSS custom propertiesWhole page, components read by variableColors, text sizes, spacing, corner radius
Css/CssPathsA set of CSS rulesWhole page, hit by selectorSupplementary rules, spacing tweaks, decorative lines, print styles
HeadHTML that goes into <head> verbatimThe whole documentmeta, external link, inline script, font declarations

All three can change appearance; the difference is “which layer they change”. The theme changes variables, the stylesheet adds rules, head injection adds document-level things. So “make the buttons rounded” is the theme’s job, “add a line to one block” is the stylesheet’s job, and “make a search engine read the page as a different title” is head injection’s job.

Head is more dangerous than the other two because it can carry <script>. A script injected there executes in this page’s source, can read things on the page, and can send requests. So do not do two things. Do not write secrets or internal addresses into Head or Css (they are all in /config and the page source, visible to anyone who opens them), and do not paste in scripts from unknown sources.

One more thing is easily confused with Head: demo.Js. It accepts a piece of JS function source that runs once after the page finishes loading, and acts on the whole document; a <script> stuffed into Head is script text the browser parses verbatim. The example uses Js to put a data-themed marker on <html>, to confirm this script really ran. It does not change appearance; it is only used to check that the loading chain is intact.

Css and Head overlap in effect: a <style> block works on either side. Divide them by “is it a document-level thing”: for page styles only, write it into Css/CssPaths, where it is managed together with the other rules; only reach for Head to add meta, an external link, or script.

19.5 The Boundaries of Binding-Level Frontend Scripts

The fourth item is not entirely about appearance. You can attach a piece of JS to a binding, and it runs once before the request is sent out.

Func<string, object> echo = value => "**Edit Input** Server received '" + value + "'.";
edit.Click(echo, [text], [editNote], apiName: "Frontend edits input",
    js: "(t) => { return [t + '(added in the browser)']; }");

js accepts a piece of JS function source. Its parameters are this event’s inputs (one text box in the example, so one string parameter), and the return value has to be written as an array whose elements are the edited inputs. What the server receives is exactly this edited copy.

There is one point that is easy to misread. The array you return is inputs, not outputs. It is not written straight into the result cell. The result still comes from the server-side handler function. Make it return a string you want displayed directly and what appears on the page is still the server’s line. What you put in the returned array depends on how many inputs there are and what components they are.

These parameters correspond one-to-one with inputs (the injection contract covered in Chapter 17), so if you change the order of inputs, the parameter order in js has to change with it. Returning undefined or returning nothing means “leave the inputs alone”, and the request is sent as usual.

This source goes verbatim into the dependency list in /config. Anyone who opens the page can read it, and during debugging you can confirm from there “whether the piece you wrote actually took effect”. So do not put decision logic, secrets, or endpoint addresses into it — they become public.

Figure 19-11 The input box contains “Wrapping text”; the server received “Wrapping text(added in the browser)”

This is its most practical use: patch the format once. Strip the invisible characters a user pasted in, remove spaces from a phone number, normalize lowercase to uppercase. Doing these in the browser costs a few milliseconds, and the server does not have to run an extra pass for them.

The second piece of JS demonstrates something else.

Func<object> serverSays = () => "**Edit Page** The server ran too.";
dom.Click(serverSays, null, [domNote], apiName: "Frontend edits the title",
    js: "() => { document.title = 'Title changed by the frontend'; }", jsRunsInBrowser: true);

This JS only changes the browser title and returns nothing. After the click the browser title changes, and the server still ran once.

The name jsRunsInBrowser sounds like “runs only in the browser, not sent to the server”. It is not. Open /config and the dependencies contain only two fields, js and js_implementation; js_runs_in_browser is not there at all. The parameter is merely accepted, not passed on. So writing true and writing false behave the same.

To “complete an interaction entirely on the frontend”, the way is to bind no server-side handler function and attach the event listener yourself with Head or Js. The binding route cannot avoid the request.

The third piece demonstrates the boundary.

check.Click(accept, [text], [checkNote], apiName: "Frontend edit plus validation",
    js: "(t) => { return [t + '(added in the browser)']; }",
    validator: (Func<string, string?>)OnlyOk);

The frontend edits the input, and the server validates as before. The validator sees the edited copy and rejects it if it does not recognize it.

Figure 19-12 The frontend added a suffix, the validator only accepts ok, the request was rejected, and the status line did not move

Put the three together and the boundary becomes clear.

  • It can change what is submitted. The return value of js becomes this request’s inputs, and the server gets the edited copy;
  • It can change the page. DOM, title, style classes — anything the browser can touch;
  • It cannot change “whether it is accepted”. Validation, permissions, and idempotency live on the server; nothing the frontend does gets around them;
  • It cannot compute for the server. No js return value means no output, and the server-side handler function runs as usual; to skip the request you have to write a separate script.

So frontend scripts suit three things. Patch the format once (strip whitespace, normalize case, turn full-width commas into half-width), give instant feedback (gray it out on click, change the title first, do not make the user wait), and block one obvious mistaken action (do not send the request on empty input). The three share one trait: getting them wrong is not fatal, because the server checks again.

What they do not suit is just as clear: business rules (“can an order still be placed this month”), permission checks (“may this person edit”), and idempotency (“has this charge already gone through”). Writing these into js is putting the rules in the browser to execute. Switch clients or send one curl and the rules are gone.

When js is used with a validator, the order is fixed. The frontend script runs first, the validator runs second. The example’s third line does exactly that. js adds a suffix to the input, and the validator sees the suffixed copy, so “Wrapping text” becomes “Wrapping text(added in the browser)”, the “ok” rule no longer matches, and the request is rejected. This order is why js cannot be used to “fool validation”. It changes the very thing the validator looks at; changing it only makes rejection more likely.

There is one more syntactic limit you will hit while writing. A binding with js needs a delegate variable; you cannot put the lambda directly in the parameter slot.

Func<string, object> echo = value => ...;      // declare it first
edit.Click(echo, [text], [editNote], js: "...");  // then pass it in

Writing edit.Click(v => ..., [text], [note], js: "...") directly raises CS1593. The compiler assigns the lambda to a different overload that has no inputs; that overload’s first parameter is Func<object?>, which cannot accept a lambda with parameters. Switch to a method group or an explicitly typed delegate variable and it works.

19.6 Chapter Summary

Appearance has four layers, each covering one segment.

Built-in themes take one line, demo.Theme = new SoftTheme(), or a lookup by name, ThemePresets.Get("ocean"). Twelve names, in essence twelve sets of CSS variables; /theme.css shows the current set directly.

Tuning parameters are eight parameters: three hues, two size steps (text size, spacing), one corner-radius step, and two font lists. Each expands into a color scale or a set of sizes, so changing one parameter moves a whole region. Hue governs color, text size governs text, spacing governs padding and gaps, and corner radius governs how hard or soft the edges are.

Variable overrides are Set("primary_500", "#7c3aed"): drop the -- from the name and turn hyphens into underscores; a mistake throws ArgumentException on the spot; GetValue reads the current value, Dump/Load save and load a whole theme, and Set(ThemeOptions) is the strongly typed form. In order, construct the theme with tuning parameters first, then override point by point.

Stylesheets take two routes, inline and file, finally joined into the css field; rules are page-wide and hit specific components through elemId and elemClasses; when writing rules use theme variables rather than hard-coded colors. Head injection goes into <head> verbatim, adding over the stylesheet the document-level things: meta, link, script.

Frontend scripts hang on bindings. With no js return value they can only change the page; with a return value they change this request’s inputs. jsRunsInBrowser never reaches the config, so writing it changes no behavior; validation, permissions, and business rules all live on the server, beyond the frontend’s reach. A binding with js needs a delegate variable; you cannot stuff the lambda into the parameter slot.

Here are the places this chapter easily goes wrong, gathered together to check against as you write.

  • Theme written after Launch: no effect, and no error;
  • Colors.Find("Violet"): wrong case, returns null, and the theme quietly falls back to the default color;
  • Set("--primary-500", ...): Set does not accept the CSS spelling, only primary_500;
  • Changing only primary_500: rest correct, hover still the old color;
  • Hard-coding #7c3aed in Css: this rule does not follow when the theme changes;
  • Selecting components in the stylesheet without writing elemClasses: the range hit is larger than you intended;
  • Writing a lambda directly in a binding with js: CS1593; catch it with a delegate variable first.

After changing appearance, run a regression. Pick three to five key bindings and click through them once, confirming the buttons are still wired to their original handler functions. Changing a theme should not move behavior, but “should not” is a design intent, not a guarantee. A wrong script in Head, or CSS that covers a button so it cannot be clicked, turns an “appearance change” into a “functional failure”.

The relation of the four layers is laid out in one figure, ordered from global to local.

Figure 19-13 The scope of the four layers, and the things they cannot change

The column in the lower-right of the figure is a different matter: the structure of the component tree, which handler function a binding connects to, whether the validator accepts, and business rules and permissions. None of these four are in the hands of the four layers. They are the content of Chapters 4 through 17, living on the server and inside using. Aiming appearance tools at these four only gets you “looks fixed, problem still there”.

Beyond these four layers, a component’s own parameters can change appearance too: variant, size, scale, minWidth, elemClasses. These say “what this one spot should look like”, while the theme says “what the global default looks like”. When the two conflict, the component parameter wins, because it is the nearer one. So when tracking down “why does this button look different from the others”, look at its own parameters first, then the stylesheet, and only then the theme.

Appearance is the last layer and the one most often revisited. It touches neither structure nor behavior, so getting it wrong only makes things ugly. That is why it belongs after the functionality has stabilized, followed by a check that the key bindings are still there.

The next chapter settles “who is allowed in to look”: authentication and access control.

Chapter 20. Authentication and Access Control

The workbench in the first nineteen chapters works the moment you have its address. This chapter adds a door to it. People who do not know the password cannot get in; those who do get in still see the same pages as before, plus one more page, Access.

Opening the door is two assignments.

demo.Auth = GradioAuth.Accounts([("alice", Password("alice")), ("bob", Password("bob"))]);
demo.AuthMessage = "This workbench is for me and one colleague only. The accounts have already been assigned; the passwords are on the machine that launches it.";

The other matter is API visibility, which decides whether a given API exposes its name and recognizes its name. This chapter treats the door and the curtain separately, and ends with what a visitor sees while the door is closed.

Why save this for Chapter 20? Because the examples in the first nineteen chapters all assume “only you are using it.” Session state (Chapter 14), the upload directory (Chapter 12), and the queue limit (Chapter 15) are all designed on the premise of “local machine, single user, trusted.” Adding a door does not turn those premises into “multi-user.” It only keeps people who should not get in from getting in. To truly share it among several people, what you change is how state and storage are divided, and that is work at another layer.

Let me set the boundary first, so expectations do not run ahead. What this chapter does is “add a door to a local application,” not build a user system. Registration, password recovery, roles, and auditing are all absent. Chapter 1 explained this positioning, and Chapter 14 also said “a session is not a user.” If you need those things, you have to move the accounts into a database and let a real identity service handle authentication, which is a different topic.

20.1 Single-Account and Multi-Account Authentication

Blocks.Auth takes a GradioAuth, and there are three ways to build one.

demo.Auth = GradioAuth.OneAccount("alice", "wonderland");
demo.Auth = GradioAuth.Accounts([("alice", "wonderland"), ("bob", "builder")]);
demo.Auth = GradioAuth.Verify(Check);   // covered in 20.2

After the assignment, demo.RequiresLogin is true. This property is read-only, for self-checks. Print one line to the log at startup and you know whether the door was opened this time.

The example uses the second form, one account for yourself and one for a colleague. The password is read from an environment variable, falling back to a demo value that runs as-is when it is not set; the demo value is written in the code, the real password is not.

static string Password(string name) =>
    Environment.GetEnvironmentVariable($"BOOK_{name.ToUpperInvariant()}_PASS") ?? $"{name}-demo";

demo.Auth = GradioAuth.Accounts([("alice", Password("alice")), ("bob", Password("bob"))]);

If BOOK_ALICE_PASS is set, it uses your own; if not, it is alice-demo. The example wants people to be able to run dotnet run and get straight in, so it keeps a default; when you put it to real use, set the environment variable and not one line of code has to change.

If the username, the password, or the list has any empty item, it throws ArgumentException on the spot. OneAccount("", "x") throws An account needs a username.; OneAccount("a", "") throws The account 'a' needs a password; an empty one admits anyone who guesses the name.; Accounts([]) throws An application protected by accounts needs at least one. The first two concern an empty username or password, the third an empty list. The messages are worded this bluntly because they are blocking a real accident: a password configured as an empty string lets anyone in.

The default deserves a mention of its own. alice-demo is there so that someone can git clone and get straight in; but it also means on a machine with no environment variable set, anyone can use that password to get in, and the UI looks no different. Login succeeds, the page is normal, everything goes smoothly. Before deploying on a shared machine, first confirm those two environment variables really are set. The self-check is simple. Try logging in once with alice-demo; if you cannot get in, they are set correctly.

Duplicate usernames do not throw; the later one overwrites the earlier one. In Accounts([("a","1"),("a","2")]), a/1 evaluates to false and a/2 to true. This is easy to trip over when changing a password. The list keeps the old line and the new one is written after it; it looks like both lines are there, but only the last one actually counts.

After you set Auth, anyone not logged in who opens any page gets this card.

Figure 20-1 With the door closed, a login card; on the card is that AuthMessage sentence

Note it appears on any page — /, /text, /access are all the same. It is not “the home page blocks you, the other pages let you through.” The card’s copy comes from AuthMessage, rendered as HTML, so you can put links and bold text in it; omit it and the page’s own default line is used.

What Happens Along the Login Path

The “Log in” button on the card sends POST /login with a form-encoded body and two fields, username and password. Success returns 200 and one line, {"success":true}, with two Set-Cookie headers in the response.

access-token-<suffix>=<token>; path=/; samesite=lax; httponly
access-token-unsecure-<suffix>=<token>; path=/; httponly

The two names differ by just the unsecure segment and hold the same token. The one with samesite=lax is for normal same-site requests; the one without is a fallback when “cross-site is rejected.” httponly means the page’s scripts cannot read it, so XSS cannot steal it. The suffix in the name is generated randomly at process startup, so old cookies naturally stop working after a restart. That suffix was originally meant to tell different processes apart; it has nothing to do with the security design.

After login the browser automatically sends both on every request, and the server recognizes you by the token. There is no JWT anywhere in this chain, no refresh token, and the cookies carry no expiry. The token lives in the server process, and a restart invalidates all of them. That is just right for a local application; delivering it to others calls for another approach.

You can walk this path with curl; it shows each step more clearly than clicking in the UI.

curl -i -X POST http://127.0.0.1:7860/login -d "username=alice&password=alice-demo"

On success you see those two Set-Cookie headers; on failure it is 400 and one line, Incorrect credentials. (details in 20.5). Add -c cookies.txt and you can then hit /config directly with the cookie, without opening a browser.

One thing to accept. The login card is not a page you drew. Its address, field names, cookie names, and failure copy are all fixed by the framework; the only thing you can change is that one sentence on the card (AuthMessage). Its appearance does follow the theme, though. After the frontend loads it fetches /theme.css on its own, so the card and the page you see after login share one color scheme (the example’s card is that purple). But its tab title is empty. The shell returned when not logged in has no <title>, so the browser tab shows the address.

The three forms, each with whom it suits, gathered together.

Figure 20-2 Three forms, but on the server they are the same thing: one login exchanges a pair of cookies, and every request after that carries them

Verify gets its own section next. Here let us first settle “when to use which.”

  • Only you use it: OneAccount. Changing the password means editing code and restarting.
  • You plus one or two colleagues: Accounts. One account each, so if something goes wrong you can tell who it was.
  • Accounts will change, or you need logging and rate limiting: Verify.

All three lack the same set of things: there are no roles (everyone is the same once inside), and there is no “remember me” or password-change entry point either. The two accounts in Accounts have exactly the same permissions. To split permissions you have to check Request.UserName yourself in the binding (used in 20.3), or simply run two applications.

In a multi-page application this door is global, not opened page by page. The example sets Auth once and every page is blocked together; there is no “this page is public, that page needs login.” To make part of the content public you have to run two applications, or judge Request.UserName yourself within one application. The latter is “dividing permissions among people inside the door,” which is a different matter from “whether the door opens.”

One consequence is easy to overlook. Someone not logged in cannot see the navbar. Navigation is part of the page content, and the empty shell has no content. So an outsider only knows the address is alive, not how many pages are behind it or what they are called. This says more about how “blocking” is implemented than the status code does: the page is sent back as usual, just with nothing inside it.

The timing of the assignment is the same as for themes: Auth must be set before Launch. Chapter 4 explained that the page is sealed on the first request; changing it after sealing has no effect and raises no error.

20.2 Custom Verification Functions

When accounts are not written in code, use Verify. It has two overloads.

GradioAuth.Verify(Func<string, string, bool> rule);
GradioAuth.Verify(Func<string, string, CancellationToken, ValueTask<bool>> rule);

The parameters are the name and password the user submitted, passed in as-is. The synchronous version suits “read a dictionary, compare a hash”; the asynchronous version suits “ask somewhere else,” querying a database or calling an identity service.

The example’s lab project gives the complete shape of the third form. Accounts live in accounts.json, the table stores the SHA-256 of the password, and the rule re-reads this file every time.

static bool Check(string userName, string password)
{
    var path = Path.Combine(AppContext.BaseDirectory, "accounts.json");
    if (!System.IO.File.Exists(path)) return false;

    var table = JsonSerializer.Deserialize<Dictionary<string, string>>(System.IO.File.ReadAllText(path));
    if (table is null || !table.TryGetValue(userName, out var expected)) return false;

    var actual = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(password)));
    return CryptographicOperations.FixedTimeEquals(
        Encoding.ASCII.GetBytes(actual),
        Encoding.ASCII.GetBytes(expected.ToUpperInvariant()));
}

The three decisions are these. First, re-read the file every time. Adding an account or changing a password needs no restart; the change takes effect on the next login. A real project swaps this block for a database query, edited the same way.

Second, compare hashes, not passwords. If the file leaks, what is taken is a hash, not a password you can use directly. SHA-256 without salt only suits this “two accounts on a local machine” case. The same password hashes the same way in two tables, and that can be seen. For proper storage, use a salted slow hash (PBKDF2, bcrypt, Argon2); that is a cryptography topic.

Third, compare with FixedTimeEquals. Ordinary == on strings returns at the first differing character, so the time depends on “how many leading characters match.” A fixed-length comparison walks both sides to the end, so the time depends only on length. Whether this can be exploited over a network depends on how much noise there is; but it costs only one extra method call to write, so there is no reason not to.

What you store the password as also depends on what it has to stop. The example’s accounts.json stores SHA-256, without salt. That stops “the file being glanced at in passing,” not “someone taking the file and computing at leisure.” The same password on two accounts computes to the same value; two identical rows of hash tell you those two people used the same password. To store it properly you need a salted slow hash. One random salt per account, a hundred thousand rounds of hashing, so that “one guess” goes from microseconds to tens of milliseconds. Rfc2898DeriveBytes.Pbkdf2 is in the standard library; no package to install.

A slow hash brings a new problem. One login takes tens of milliseconds, and an attacker guessing once also takes tens of milliseconds. That is a deliberate cost. When you really reach the scale where you must stop brute force, you add rate limiting, not turn the round count down.

A rule has to keep two conventions. One: only answer true/false; to reject, return false. Let the rule throw an exception and the browser gets a 500, with the error notice, retries, and logs all changing shape. Two: empty values are passed in as well. Run it once with a rule that only prints its parameters. Submit empty strings for both username and password, and the rule receives two empty strings; the framework does not screen them out for you first. So “reject an empty password outright” is something you write yourself, or you let the hash comparison handle it. The hash of an empty string does not equal any record, so it is naturally false.

When you need to ask somewhere else, switch to the asynchronous version; the shape is the same, you just turn “look up” into “wait for.”

GradioAuth.Verify(async (userName, password, cancellation) =>
{
    var record = await Accounts.FindAsync(userName, cancellation);

    // When the name does not exist, run once against a fixed dummy record; the timing matches a real record, so you cannot ask whether the account exists.
    var salt = record?.Salt ?? Hasher.DummySalt;
    var expected = record?.Hash ?? Hasher.DummyHash;

    var hash = await Hasher.SlowHashAsync(password, salt, cancellation);
    return record is not null && CryptographicOperations.FixedTimeEquals(hash, expected);
});

When two login requests arrive at the same time, the rule is called twice at once. It is an ordinary handler function, not a queued task. So if the rule counts failures or writes a log file, think through the concurrency first; increment with Interlocked, or just write the count into a database.

CancellationToken is the one for when the request is cancelled. Closing the browser page or a request timeout triggers it. A database-backed implementation has to pass it down, otherwise one stuck login holds a connection open.

Besides “judging right or wrong,” a rule can also do a few things the framework does not manage: write one line of log (who, when, succeeded or not), count failures by source, shut out sources with repeated failures, and let only certain accounts in during a maintenance window. That is what “your own rule” is for. Accounts does one thing; Verify can do anything, at the price that you also own the mistakes.

The lab project switches among four cases with an environment variable, so you can compare them directly.

$env:BOOK_AUTH="one"       # one account (password alice-demo)
$env:BOOK_AUTH="accounts"  # a set of accounts: alice and bob, passwords are the name plus -demo
$env:BOOK_AUTH="verify"    # reads accounts.json, compares hashes
$env:BOOK_AUTH="none"      # no Auth is set, anyone can get in
dotnet run --project samples-en\chapter20\lab

A custom rule has four kinds of input to walk through first: the correct account and password, a correct account with a wrong password, an account that does not exist, and both empty strings. The fourth falls through naturally to false when there is no dedicated branch. The hash of an empty string does not equal any record, so the comparison gives false; but if the rule contains a branch like “if the name is empty, let it straight through,” that becomes a successful login, and the UI shows nothing unusual.

The none case is not there just to fill out the list; it lets you see what “no door” looks like. The page is the complete workbench directly, and Request.UserName in the handler function is null. Adding or not adding authentication does not change one character of component code; that is a fact the next sections use again and again.

20.3 The Login Button and Logged-Out Behavior

The login card is not drawn by your page. It is an empty shell page drawn by the frontend. When not logged in, the HTML the server returns has window.gradio_config carrying auth_required: true and auth_message, while components and dependencies are both empty and pages holds only one empty string. Seeing auth_required, the frontend does not draw your UI and draws a form instead.

This also explains something easy to misunderstand. Visiting /text when not logged in gives HTTP status 200, not 403. The page itself has to open before the login card can be drawn. What blocks the content is this empty shell, with nothing inside it.

The name gr.LoginButton makes it easy to assume it is “the login button for password authentication.” It is not. It belongs on the OAuth path. Its default text is Sign in with Hugging Face, and clicking it sends the browser to /login/huggingface. That address is registered by the button itself. With no gr.LoginButton on the page it is 404; put the button there without an OAuth provider configured and it returns 500. Not 404, and not a “not configured” line either. On a page holding only this button, after login the button text still has not changed to “Log out,” and clicking it still heads for that 500.

Someone will ask: why not just use HTTP Basic authentication? The browser brings its own dialog, and not one line of configuration is needed. Three reasons. One, that dialog is not yours to control: you cannot change its copy, cannot put a link in it, and cannot even write “what this application is called” into it. Two, you cannot log out. Basic credentials are cached by the browser and the standard has no “log out” action; close the tab, open it again, and you are still logged in. Three, it sends the password along with every request, instead of a token that can be revoked.

The framework chose a form plus cookies. One extra request buys a customizable card, a link that really logs out, and a token the server remembers.

So applications using password authentication do not use it. The example places not one. When the “log in” action is needed, what the user does is fill in the account on the card, and the framework has already supplied that card.

Conversely, logging out has no button, but it has an address, /logout. Open it with the cookie and the server clears those two cookies in the browser, then 302s back to the home page; the home page becomes the login card again. The example puts this on the Access page.

gr.HTML("""<a href="/logout">Log out</a>""");

There is one detail here. Do not use a Markdown link. [Log out](/logout) renders an <a> with target=_blank, so clicking opens a new tab. The new tab is back at the login card, while the original tab still holds the old content, which looks as if logging out failed. A hand-written <a> has no such attribute and navigates away in the current page. Try each of the two forms once; the difference is exactly that one attribute.

Logging out also invalidates this account’s token. This runs against the “only clears cookies” intuition; you only see it clearly by running the experiment. Log in, note the cookie value, /logout, then put that same pre-logout value back into the request header. /config returns 401, /gradio_api/user returns null. The server has deleted the token straight out of memory.

The scope of invalidation is the account, not this one login. Open two tabs, log in once in each with the same account, and you get two different tokens; log out one of them and the other also returns 401. Log in with a different account (bob), and after logging out alice, bob is still 200; invalidation goes by username.

The exception is an application with gr.LoginButton on the page. Then /logout is handled by the OAuth route, and old tokens still return 200 after logout (a page holding only that button verifies it). The example places none, so everything in this section is about the password-authentication path.

Restarting the application invalidates all tokens at once. They live only in the process’s memory and are never written to disk. To take the account in the current browser offline immediately, log out; to take all accounts offline together, restart.

After a successful login the page content is replaced, but the address does not change. In the example you log in at /access and are still at /access afterward; only the login card has become that page’s body. This page change is a full reload. The path in the address bar is kept as-is, so deep links and the current page survive; but temporary state in the page that was not submitted is refreshed away. Hang a marker on window before login and after login it is gone.

After login, “who is operating” is available on the server side: add a Request to the handler function’s parameter list.

Func<Request, object> answer = request =>
{
    var name = request.UserName ?? "(empty)";
    return $"**Who is operating** username `{name}`, session `{request.SessionHash}`.";
};

ask.Click(answer, null, [who], apiName: "Ask identity");

Request is not a component and does not go into inputs. It is an extra parameter the framework injects by type; you can write it at any position in the parameter list, or write only it. UserName is the logged-in account behind this run, SessionHash is the session id (Chapter 14). When the application does not require login, UserName is null. That is what the none case at the end of 20.2 looks like.

Figure 20-3 The home page after login; when not logged in, the same address gives only the login card

Figure 20-4 The Access page: the top line is Request.UserName, and the three buttons below differ only in apiVisibility

Putting identity into the UI has another use. With several accounts, write one line on the page, “current account alice,” and the user knows whose session they are using. That is not a small thing when several people share one machine. Chapter 14 counts a session as “one page load,” so two people each opening a tab have two separate states; who changed what can only be matched up by the session id. Session state (Chapter 14) is divided by session; switch accounts and it is a different one. If you do not write this out, users will think “my input was lost.”

20.4 Authentication and API Visibility Layered Together

Everything so far has been about “blocking the page.” The page is only one entry point; the API has to be defended too. A script does not need your page — it just POSTs directly.

What does the API give when not logged in? 401, plus one line for the frontend to display.

{"detail":{"error":"Not authenticated","auth_message":"This workbench is for me and one colleague only. The accounts have already been assigned; the passwords are on the machine that launches it."}}

This auth_message is AuthMessage, so you write the custom notice in one place and both the page and the API follow. The list is “APIs outside the page”: /config, /gradio_api/info, /gradio_api/queue/join, /gradio_api/run/..., /gradio_api/call/..., /gradio_api/file=... are all behind this gate; outside the door are the things the login page needs itself — the theme stylesheet /theme.css, frontend assets, /login, /logout.

Two exceptions. /gradio_api/user returns 200 even when not logged in, with null as its content (“no one” is also an answer); /gradio_api/login_check returns 401 when not logged in, and after login 200 plus a null. The frontend uses these two addresses to decide “whether to draw the login card.”

The two answers, page and API, set side by side.

Figure 20-5 The same door, two ways of answering: the page gives an empty shell, the API gives 401

So “blocking the page” and “blocking the API” are not the same thing, and not one gate either. The page works by “giving no content,” the API by status code; the only way to skip login by editing the frontend is to call the API, and the API judges for itself.

Once the door is open, the second layer comes into play: API visibility. apiVisibility on a binding has three values.

Figure 20-6 Visibility governs the API, not the UI; all three buttons can be clicked on the page

  • ApiVisibility.Public (default), enters /gradio_api/info, and can be called by name.
  • ApiVisibility.Undocumented. Does not enter /info, but can be called by name, and once you get the event_id you carry on as usual.
  • ApiVisibility.Private. Does not enter /info, calling it by name returns 404, with the body Could not infer function index for API name: Visibility private.

Note that 404 line. It says “this name is not recognized,” not “you have no permission.” That is deliberate. To the frontend a private endpoint does not exist, and it gives the same answer as “this name is misspelled,” so someone probing names cannot work out which name is real.

/gradio_api/info is that list. When someone else wants to write a script against you, the first step is to fetch it and see which endpoints exist. So “whether to expose” amounts to “whether this counts as your public API.” Setting an intermediate step to Private says “this step is internal to the UI, do not use it as an API”; setting it to Undocumented says “it works, but is not recommended and not guaranteed.”

The order in which the three layers stack is: authentication → visibility → handler function. Authentication is the outermost; without logging in you cannot even ask “does this name exist” (401, not 404); only after login does visibility say “whether this name is exposed and recognized.”

Why can all three buttons on the page be clicked? Because page submission goes through /gradio_api/queue/join carrying an fn_index, not a name. Visibility governs “names,” and the UI uses no names, so it cannot stop your own people from clicking the buttons. That is by design, not a hole. Private is a boundary set for scripts, not for users.

In the example the three buttons’ bindings differ only in apiVisibility; their names are all different.

open.Click(() => "**Public** listed in `/gradio_api/info`, and callable by name.", null, [result],
    apiName: "Visibility public");
undoc.Click(() => "**Undocumented** not in `/info`, but callable by name.", null, [result],
    apiName: "Visibility undocumented", apiVisibility: ApiVisibility.Undocumented);
closed.Click(() => "**Private** not in `/info`, and calling it by name is not recognized — the UI still works.", null, [result],
    apiName: "Visibility private", apiVisibility: ApiVisibility.Private);

apiName is required. Visibility is about “whether this name is exposed,” and with no name there is nothing to talk about. How names are formed and what the framework puts together when you omit one is covered in Chapter 22.

To verify, you do not need to open the UI; use the three curl commands below (the details of job-style calls are also in Chapter 22).

curl -s -b cookies.txt http://127.0.0.1:7860/gradio_api/info        # list which names are in the list
curl -s -b cookies.txt -X POST http://127.0.0.1:7860/gradio_api/call/%E5%8F%AF%E8%A7%81%E6%80%A7%E5%85%AC%E5%BC%80 -d '{"data":[]}' -H "Content-Type: application/json"
curl -s -b cookies.txt -X POST http://127.0.0.1:7860/gradio_api/call/%E5%8F%AF%E8%A7%81%E6%80%A7%E7%A7%81%E6%9C%89 -d '{"data":[]}' -H "Content-Type: application/json"

Those two strings in the path are the UTF-8 percent-encoding of Visibility public and Visibility private. Write non-ASCII characters directly into the URL and Kestrel returns 400 before routing, with an empty body. The reason is that the request line itself is invalid, and has nothing to do with authentication.

The first returns the endpoint list; the second an event_id; the third 404 and that Could not infer function index line. Without the cookie all three are 401, so do not forget the order.

How to choose in practice: default to Public; use Private for bindings only your own page uses (say an intermediate step), so nobody treats it as an API; use Undocumented for “works, but I do not want it in the docs.” The example’s Access page puts the three buttons side by side precisely so this difference is visible in a single UI.

20.5 How Authentication Failures Are Presented

Type the password wrong and the user sees something like this.

Figure 20-7 Bad credentials: a red line above the card, both input boxes cleared, focus left on the login button

That red line on the card does not come from the server. The server sends 400 plus one English line, Incorrect credentials.; what the card shows is a line the frontend translated itself, “Incorrect credentials.” It maps by status code and does not read the body. Replace the 400 body with some other English sentence and submit again, and the card still shows those same words. This has two consequences. Changing AuthMessage does not change the failure notice (that sentence appears only on 401 and at the top of the card); to give “Incorrect credentials.” different wording, you edit the frontend language pack, not this.

What the backend gives is 400, one body line.

{"detail":"Incorrect credentials."}

This line is identical character for character in three cases: wrong password, username that does not exist, empty password. Compared three responses byte by byte with curl, all are 35 bytes, the bodies exactly the same. That is how “not leaking whether an account exists” is done. If a nonexistent username returned “User not found,” an attacker could first screen a list of email addresses, then try passwords only against accounts that exist.

Besides explicit failure there is a category of “the format is simply wrong.” When the request has no username or password field at all, it returns 422.

{"detail":[{"type":"missing","loc":["body","username"],"msg":"Field required","input":null},
           {"type":"missing","loc":["body","password"],"msg":"Field required","input":null}]}

The two need to be told apart. 422 means “you did not submit in the right format,” 400 means “you submitted, but it is wrong.” The frontend only translates 400 into “Incorrect credentials.”; 422 is not reachable on the normal path. The two boxes on the card always submit.

Accounts and OneAccount answer the same way because outwardly they answer only one question: do these credentials work. Name does not exist, password wrong — the answer is false either way, with exactly the same status code and body. They do not promise the timing is the same too; to control timing as well, use Verify, compute a hash first, then look up the table and compare.

When you write Verify yourself, you have to guarantee these two things: the same answer, and timing as close as possible. The counterexample is common.

// Don't write it this way: returning early when the name does not exist makes the timing different from "name exists but password is wrong"
var record = table.FirstOrDefault(x => x.UserName == userName);
if (record is null) return false;
return SlowHash(password, record.Salt) == record.Hash;

When the name does not exist, not one slow hash is computed; when it exists, one is. That time lands on the response, and averaging over many requests makes it distinguishable. Swap the order: compute the hash first, then look up the table and compare; compute it as well when the name does not exist.

Two more things that are easy to get wrong. One: do not lock by username. “Lock for ten minutes after five wrong tries” sounds safe, but what do you return while locked? Return “Account locked” and you have told the other side the account exists; return “Incorrect credentials.” and the user does not know they are locked. For a local application, simply do not lock at all; if you must, do it by source IP and accept the collateral damage that brings.

Two: do not write passwords into logs. Verify receives the plaintext password, and a casual Console.WriteLine is convenient, but logs get copied and pasted into chat windows. If you log, log the name, the time, and the result — not the password.

One last distinction. A failed login does not produce the error block from Chapter 17. That block pops up when a run in the queue fails, and login never enters the queue. It happens before the page gets its config, when the frontend has not even drawn your UI yet. So the notice for bad credentials is on the card and the notice for run-time errors is in the panel: two separate things; do not expect to see them in one place.

One last point about the current state: login has no rate limiting. Repeated wrong tries do not slow down, do not lock, and do not raise a CAPTCHA. Two people on a local machine are fine; the day you put it on an intranet, put a reverse proxy in front for rate limiting, or count by source yourself inside Verify. The framework offers no rate-limiting configuration item, and there is no such implementation in the code.

20.6 Chapter Summary

After adding a door, the changes land in these places.

  1. One line, demo.Auth = GradioAuth.Accounts(...), opens the door. The three forms (OneAccount, Accounts, Verify) cover “just you,” “a few colleagues,” and “accounts stored elsewhere.” An empty password throws on the spot; a duplicate username is overwritten by the later one.
  2. The door and the curtain are two layers. Authentication decides “whether you can get in,” visibility (apiVisibility) decides “whether this name is exposed and recognized.” Authentication is the outermost; without logging in you cannot even ask about a name.
  3. Page 200, API 401. When not logged in the page is still sent, but it is an empty shell (auth_required: true, components and bindings all empty); the APIs uniformly return 401 with auth_message in the body. Blocking the page is not blocking the API.
  4. Failure is always the same one line. Wrong password, nonexistent user, empty password — all 400 Incorrect credentials., byte for byte. A custom rule has to hold this line itself, and also hold “compute the hash before looking up the table.”
  5. What logout invalidates is the account. /logout clears those two cookies in the browser, the server deletes this account’s token along with them, and replaying the old cookie returns 401; another tab of the same account fails together with it, while other accounts are unaffected.

This chapter only handles “who can get in.” How to coexist with the host once inside, and how to expose capabilities as APIs, are Chapters 21 and 22 respectively.

The cost of this chapter should be stated too: one more password to maintain (or one more account table), one more deployment risk of “forgot to set the environment variable,” and one more boundary to remember in “logout invalidates by account, restart invalidates by process.” What you get in return is that when you send the address out, you no longer have to worry that the recipient will casually click it open and see your drafts and records.

Finally, a self-check list; go through it in order when you wire this into your own application.

  • Print one line of RequiresLogin in the startup log to confirm the door really opened this time;
  • Open every page in a browser that is not logged in and confirm all you see is the login card;
  • Use curl to hit /config and one apiName directly and confirm both are 401, not 200;
  • After login, open /gradio_api/info and count the exposed endpoints to see they match expectations;
  • Log out, open the page again, and confirm you are back at the card;
  • Change one sentence of AuthMessage and confirm both the page and the 401 carry the new sentence.

Chapter 21. Host Integration

The examples in the first twenty chapters all start from the same line, demo.Launch(). That one line builds the application and the host together. Address, port, logging, and the life and death of the process are all decided for you. For a local tool that is just right; but as soon as the application has to live in the same process as something else, that one line is no longer enough.

This chapter moves the workbench into an ASP.NET Core host and uses what the host provides. Business services in the container, values from configuration, logging, health checks, and a stopping process that can wind things down.

Look at the skeleton first. The example’s Program.cs no longer builds the application directly at the start; it builds the host first.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGradio();
// ...register this workbench's own services
var app = builder.Build();

The pages are still written with gr.Blocks(); once they are written, UseGradio mounts them into the host.

var demo = gr.Blocks(title: "Personal Local Workbench");
using (demo)
{
    Home();
    using (demo.Route("Text", "text")) { TextPage(); }
    // ...the other eight pages
}

app.UseGradio(demo);
app.Run();

demo is still that demo, and the pages are still those pages. What changes is who owns the process. Before, it was Gradio’s standalone host; now it is your ASP.NET Core application.

Draw the boundary first. This chapter is about “mounting it in” and “what the host gives you”. Exposing capabilities as callable interfaces is Chapter 22. Authentication still works as it did in Chapter 20; this chapter does not cover it again.

21.1 Standalone Host and Self-Built Host

The first twenty chapters use a standalone host. demo.Launch() builds a web host internally that serves only this application, then holds the calling thread until the process is stopped. The address defaults to 127.0.0.1, the port defaults to 7860, and the framework configures logging itself. Apart from this UI, there is nothing else in this process. No endpoints of your own, no other background tasks, and no container that you decide.

The standalone host has a second form, where you build the host object yourself.

var options = new GradioServerOptions
{
    ServerName = "127.0.0.1",
    ServerPort = 7860,
    HealthCheckPath = "/health",
};

await using var host = new GradioServer(options);
await host.StartAsync(default);
Console.WriteLine(host.BaseAddress);

await host.StopAsync(default);

GradioServer and Launch are the same set of things. It registers the same services and mounts the same route table; it simply spreads the options out and hands startup and shutdown back to you. When StartAsync returns, the service is already listening; when StopAsync returns, it has already stopped. The example’s lab project uses exactly this.

It builds its own container, so the pages have to be written before the host is built. What lab does is first write the pages with gr.Blocks(), then register that one into the container through ConfigureServices.

var page = gr.Blocks(title: "Host Playground: GradioServer");
using (page) { /* write the page */ }

var options = new GradioServerOptions
{
    ConfigureServices = services => services.AddSingleton(page),
};

await using var host = new GradioServer(options);

After startup, print a line to check: ReferenceEquals(host.Blocks, page) is True. What the container serves really is the one just written, not an empty page it built on its own. Without this step, the pages are written onto an object nobody serves, and the browser opens to a blank page.

The third form is the main line of this chapter, the self-built host. The host is the ASP.NET Core application you build with WebApplication.CreateBuilder; Gradio is just one piece mounted onto it. Address, logging, container, endpoints, middleware — all of them are yours.

Launch also has a non-blocking use. gr.Launch(demo, preventThreadLock: true) returns the GradioServer to you and the calling thread keeps going. lab has verified it this way. The console first prints Running on local URL, followed immediately by a line Address returned by Launch: http://127.0.0.1:7864/; both are the same address. If you want to manage stopping yourself but do not want to touch GradioServerOptions, use this overload.

The three shapes side by side.

Figure 21-1 Three shapes, one and the same route table on the server side

How to choose depends on whether this process has anything else to do.

  • Only this one UI, for your own use: demo.Launch(). One line, nothing to manage.
  • Still only this UI, but you want health checks and want to control startup and shutdown yourself: GradioServer.
  • This process also has other services, other endpoints, other background tasks: a self-built host.

The third form is not “more advanced” than the first two; only the ownership differs. In the first two, the process exists for the UI; in the third, the UI is part of the process. To put it another way: the first two are “make the UI into a program”, the third is “put a UI inside a program”.

The phrase “the same route table” has evidence you can check. The page list of the same workbench under a self-built host has ten entries. Home plus nine addresses, 527 components, 112 bindings. These numbers come from the application itself, not from the host. Changing hosts did not remove a single page, nor did it change authentication, theme, or upload directory; those are the application’s own settings, and the host does not alter them.

One easy misunderstanding: in a self-built host, do not call demo.Launch() again. It would build another host and hold the calling thread, and the host you wanted would never get to start. The example replaces the last line with app.Run(), which is ASP.NET Core’s own startup call.

21.2 Host Options and Listening Address

The standalone host has few options, but every one of them directly decides “who can connect”.

ServerName is the listening address, defaulting to 127.0.0.1, which only the local machine can connect to. Change it to 0.0.0.0 and it listens on all network cards, so machines on the same LAN can connect too. The console still prints only one address, but what actually opens is another door. This book is positioned for single-user use on one machine, so the examples stay on the loopback address by default; before letting others connect, think about whether the gate from Chapter 20 is enough.

ServerPort is the port, defaulting to 7860. Set it to 0 to let the operating system pick a free port. Which one it picked, read from BaseAddress after startup.

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://127.0.0.1:51010
BaseAddress = http://127.0.0.1:51010/

BaseAddress is “the address to hand out”. When the port is 0, it is the one the system actually gave, not 0. Automation scripts, screenshot tools, and the code that prints the address to the user should all read it rather than build it themselves.

When listening on 0.0.0.0, the log also prints http://0.0.0.0:7863. That is not an address for the browser. On the local machine you still open 127.0.0.1:7863; another machine has to use this machine’s LAN address. Both addresses point to the same process; the only difference is “who can connect in”.

The page in a standalone host looks like this.

Figure 21-2 The lab page uses the default theme, because this page sets no theme; appearance belongs to the application, not the host

HealthCheckPath gives the health check a path; if you do not set it, nothing is mounted. ConfigureLogging adjusts logging, and ConfigureServices adds things to the container before Gradio’s own registrations. The latter is the standalone host’s only extension point, and 21.4 uses a similar approach.

In a self-built host, these knobs are no longer given directly by code. Address and port come from ASP.NET Core configuration; the example writes them in appsettings.json.

{
  "Urls": "http://127.0.0.1:7860"
}

The Urls key is read by the host, not by Gradio. It can also be overridden by the command line or an environment variable of the same name.

dotnet Chapter21.dll --urls http://127.0.0.1:7867
$env:Urls="http://127.0.0.1:7868"

Both were tested and take effect, on ports 7867 and 7868 respectively. But ASPNETCORE_URLS does not override the Urls in the file in this combination. When both are present, the one in the file wins. This is easy to remember backwards; when you go to change the port, take --urls as authoritative.

The port-conflict error is the same as before, only this time it is thrown at host startup.

System.IO.IOException: Failed to bind to address http://127.0.0.1:7860: address already in use.

In a self-built host, demo.Launch(serverPort: 7861) is no longer the way to change the port. That parameter belongs to the host Launch builds itself. To change the port, change Urls, or pass --urls at startup.

One last small thing: port 0 works well in both hosts. To run a second instance for comparison, or when a screenshot tool fears port conflicts, you can let it pick for itself and then read the actual port back from the log or BaseAddress.

21.3 Registering and Mounting in ASP.NET Core

The self-built host has only two calls.

builder.Services.AddGradio();   // kernel, application, route table
app.UseGradio(demo);            // hand in the finished page, map the routes

AddGradio registers three things: the kernel for rendering and sessions, a Blocks, and that route table. The application is held by the container. One container hosts only one application — that is its constraint, not a suggestion. UseGradio maps the route table onto the host’s endpoints and tells the container “the pages to serve are these ones”.

It does not provide an address, does not provide TLS, does not provide a reverse proxy, and does not decide where logs go for you. It only gets done the one thing “Gradio needs a container and a route table”; the rest belongs to the host. The other way around, the middleware the host already has (HTTPS, compression, rate limiting, static files) can all be added to this pipeline, and Gradio does not block it.

The order has to be spelled out, because the order the documentation gives does not work. The documentation says “first mount the routes, then write the UI into the application, finally start”, which corresponds to this.

app.UseGradio();                                  // map the routes first
var demo = app.Services.GetRequiredService<Blocks>();
using (demo) { gr.Textbox(...); }                 // then write the UI

Written this way, it throws as soon as the first button binds an event.

System.InvalidOperationException: An event binding has to belong to an application.
Bind it on a block that was added to a Blocks, or merge its triggers with Blocks.On first.

Factories such as gr.Textbox() write a line onto the page that is currently open. What opens that page is gr.Blocks(), which opens the rendering scope at the same time as it returns the application; using closes it when it ends. The Blocks in the container has not gone through this step, has no open rendering scope, so the factory cannot write into it; components then have no owner, and a binding naturally cannot find an application.

So the example uses a different overload: write the pages first, then let the host mount them.

var demo = gr.Blocks(title: "Personal Local Workbench");
using (demo) { /* home page and nine pages */ }

app.UseGradio(demo);

The example puts builder.Build() before writing the pages, because the handler functions need IServiceScopeFactory from the container; conversely, writing the pages before Build is also fine, as long as the services needed are already available then. Both orders work; the only thing that cannot change is “pages before UseGradio”.

UseGradio(demo) does two things. It registers this one page into the container, then maps the route table onto it. It must be called before the container resolves its own Blocks. Two applications living in one container is something it explicitly refuses. In the example it comes immediately after the pages, with nothing else touching the container in between.

Once mounted, the host’s own endpoints are written as usual.

app.MapGradioHealth("/health");

app.MapGet("/ping", (HostFacts facts) => Results.Text($"pong {facts.Address}"));

app.MapPost("/stop", (IHostApplicationLifetime lifetime) =>
{
    lifetime.StopApplication();
    return Results.Text("stopping");
});

/ping is the host’s own endpoint; it shares one address and one container with the workbench, but it is not in Gradio’s route table. That means two things: it is not protected by demo.Auth, and it does not go into /gradio_api/info. The example keeps it so that “two things in one process” is visible; when a real application adds its own endpoints, it has to put its own gate on them. The gate from Chapter 20 only covers Gradio’s pages and interfaces.

/stop is the switch used for verification in this chapter; it calls the very method Ctrl+C calls. A real application should not leave it in.

UseGradio only maps Gradio’s routes; the endpoints you map yourself still belong to you. The two share one address and are told apart by path. The health check is placed after UseGradio(demo) because it has to resolve the Blocks in the container, and the pages are only handed in at the moment of UseGradio(demo). Reverse the order and the check registers that empty application instead.

app.Run() blocks until the process stops, so statements written after it never execute. Things that have to happen only after startup go into the ApplicationStarted callback; 21.7 uses this.

After startup, the console no longer shows that one line Running on local URL, but a series of the host’s own.

info: Chapter21.Heartbeat[0]
      Heartbeat started
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://127.0.0.1:7860
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: xxx
info: Chapter21[0]
      Workbench started: http://127.0.0.1:7860

The address is still that address, and the pages are still those pages.

Figure 21-3 The home page under a self-built host: ten items in the navigation, the same as with a standalone host

After mounting, not one of the workbench’s own settings has moved. Theme, Auth, UploadFolder, and the queue limit are still the values assigned to demo when the pages were written. The host does not know them and does not need to. That is exactly what “the UI is part of the process” means. The process provides the container and the address; the application decides what it looks like.

After mounting, the workbench’s main flows have to be walked through again before they count. The example got these working under a self-built host. The login card appears as usual, and the right password lets you in; all ten pages open; uploads, events, and the queue are all still in their original places. None of this is automatic. If UseGradio registers one page too few, or registers it too late, the UI is empty or the process simply exits.

21.4 Dependency Injection and Business Services

Up to this chapter, handler functions have always been “use whatever is in the closure”. Chapter 3 covered where their parameters come from. Components in inputs give values by position, and Request, Progress, CancellationToken are injected by the framework by type. Beyond that, it does not know the container and will not resolve a service for you.

So “using dependency injection” has only one path in Gradio.NET. Take the service out of the container and pass it into the handler function’s closure. There are two ways to take it; the difference is “when you take it”.

The first takes it once, while writing the pages.

var desk = app.Services.GetRequiredService<WorkDesk>();
run.Click((string text) => desk.Arrange(text), [text], [body], apiName: "Clean up");

What this gets is an instance from the root container; the effect is the same as turning it into a singleton, with all sessions sharing one. In development the container stops you on the spot (scope validation); in production it gives you an instance that is never released. Neither is what you want.

The second is what the example uses. Take only the scope factory, and open a scope on each call.

var scopes = app.Services.GetRequiredService<IServiceScopeFactory>();

(object, string) DeskArrange(string text, double? width)
{
    using var scope = scopes.CreateScope();

    var desk = scope.ServiceProvider.GetRequiredService<WorkDesk>();
    var ledger = scope.ServiceProvider.GetRequiredService<RunLedger>();

    var columns = width is null or <= 0 ? (int?)null : (int)Math.Round(width.Value);
    var result = desk.Arrange(text, columns);
    var nth = ledger.Record("Clean up");

    return (result.Text, $"**Run {nth}** · Service instance `{result.Instance}`\n\n{result.Report}");
}

using guarantees the scope is released when this call ends. WorkDesk is Scoped, one instance per call; RunLedger is Singleton, shared across calls. Both services are taken from the same scope, written the same way; the lifetime is decided when they are registered.

Take the scope factory rather than IServiceProvider directly, because the scope has to be drawn by you: CreateScope() is on the factory, and the root container does not open one for you. Taking a Scoped service from the root container either gets stopped by the container or gives you an instance that is never released.

Those two columns lines are what the word “adaptation” concretely looks like. The component gives a double?, where 0 means “use the configuration”; the service wants an int?, where null means “not specified”. The translation sits in the handler function, and the service only knows its own contract.

WorkDesk itself looks like this.

public sealed class WorkDesk(IOptionsSnapshot<WorkbenchOptions> options, ILogger<WorkDesk> log)
{
    private static int _instances;

    public string Instance { get; } = $"WorkDesk#{Interlocked.Increment(ref _instances)}";

    public WorkResult Arrange(string? text, int? width)
    {
        var settings = options.Value;
        var columns = width ?? settings.MaxWidth;
        var result = TextLayout.Wrap(text, columns);

        log.LogInformation("Clean up {Chars} characters, {Lines} lines, at most {Width} characters per line",
            text?.Length ?? 0, result.Report.Lines, columns);

        var report = $"{result.Report.Lines} lines, {result.Report.Characters} characters, longest line {result.Report.LongestLine} characters";
        // ...
        return new WorkResult(result.Text, report, Instance);
    }
}

It does only three things: read configuration, call the wrapping rules in core, and write one log line. The wrapping rules themselves stay in Chapter21.Core, a project that does not reference Gradio.NET; switching to a console app, a Web API, or another UI needs no change there. The handler function is the adaptation layer: open a scope, call, and lay the result out as the type the component wants.

The handler function’s parameter list can still write Request. It is injected by the framework by type, while the service is taken from a scope by the closure; the two paths do not conflict. Request answers “who is operating”, the service answers “how the work is done”. That identity-asking button in Chapter 20 used only Request; add the service as well and both can exist together, with no change to the parameter list.

The effect is visible on the page.

Figure 21-4 The host page: on the left the result from the business service, on the right the material from the container and configuration

Click the same button three times and the service instances are WorkDesk#1, WorkDesk#2, WorkDesk#3 in turn, while the “Record” count climbs from 1 to 2, 3. One is per-call, the other spans calls. The background task’s counter is climbing too; that is a different thread of things, covered in 21.7.

Several easy places to go wrong, all of the “it runs but it is not right” kind.

  • Store a Scoped service in the closure. The pages are written only once and the closure lives until the process ends; that “one per call” service becomes a resident object, and it is released after the first request anyway, so using it again throws “already disposed”.
  • Take a Scoped service straight from the root container. In development the container stops you; once scope validation is turned off, you get an instance that is never released.
  • Forget to release the scope. You cannot see it once or twice; run it for a day and you have a pile of unreleased objects. using is the least troublesome way to write it.
  • Inject Scoped into Singleton. Again “a resident object holding a one-shot object”; the container refuses outright, which is better than finding out at runtime.

Separate two kinds of “once” as well. State from Chapter 14 counts by session, one per page load; the Scoped service here counts by call, one per button press. They are not the same thing. Put session data in a Scoped service and it is gone on the next call; put call parameters in State and they stay until the page closes.

One more thing that is not part of dependency injection but is often mentioned together with it. Do not push business logic back into the handler function. The handler function’s job is to translate the values the component gives into the parameters the service wants, then translate the service’s result into the type the component wants. Anything beyond translation (rules, computation, reads and writes) belongs to the service. The direct benefit is that the “parameter and return value contract” from Chapter 3 affects only this translation layer, and the rules themselves can be reasoned about on their own.

21.5 Providing Configuration to Handler Functions

Configuration comes in from the host, and the path is fixed: configuration source → IConfiguration → strongly typed options → service → handler function.

The example’s configuration looks like this.

{
  "Workbench": {
    "Owner": "Local user",
    "Greeting": "This workbench is now hosted in an ASP.NET Core host.",
    "MaxWidth": 24,
    "Token": ""
  }
}

Bind it into a type.

builder.Services.Configure<WorkbenchOptions>(builder.Configuration.GetSection("Workbench"));

After that any service can inject IOptions<WorkbenchOptions>, IOptionsSnapshot<WorkbenchOptions>, or IOptionsMonitor<WorkbenchOptions>. The three read values at different times. IOptions computes once, IOptionsSnapshot once per scope, and IOptionsMonitor can change on every read. WorkDesk uses Snapshot, one per call, which fits exactly.

The cost of choosing wrong is concrete. IOptions fixes the value at the first resolution, so editing the file has no effect and it looks like “hot reload is broken”; IOptionsMonitor can change on every read, which suits Singleton, but reading twice in one request can give two values and produce self-contradictory results. A Scoped service with Snapshot gets one per scope, consistent front to back.

One rule to remember about configuration source priority: a source added later overrides earlier ones. The default order is appsettings.json, appsettings.{environment}.json, environment variables, command line. Therefore.

$env:Workbench__MaxWidth="12"
dotnet run --project samples-en\chapter21\Chapter21.csproj

The “at most 12 characters per line” on the page comes from the environment variable; the 24 in the file is overridden. The two underscores are the separator for nested keys, so Workbench__MaxWidth corresponds to Workbench:MaxWidth.

Editing the file also takes effect, with no restart. After startup the example changes MaxWidth in appsettings.json from 24 to 16; the next button click wraps at 16.

**Configuration** Owner Local user · at most 16 characters per line · Password Configured (27 characters)

This holds only in services that “re-read on every call”. The password for demo.Auth is read from builder.Configuration while the pages are being written, so editing the file will not change it. Values like that need a restart to change. Splitting configuration into “hot” and “cold” is more useful than vaguely saying “hot reload is supported”. Hot means re-read on every call (MaxWidth); cold means read once while writing the pages (Greeting, AuthMessage, the authentication password). The former takes effect when you edit the file; the latter needs a restart.

The environment name also affects which file is read. appsettings.Production.json overrides appsettings.json, and appsettings.Development.json is layered on only when ASPNETCORE_ENVIRONMENT=Development. The example has neither file, so the Hosting environment: Production line in the log is the default.

You can also read configuration while writing the pages. builder.Configuration["Workbench:Greeting"] is available even before builder.Build(); the example’s Greeting and AuthMessage are both read this way. Its difference from IOptions is “how many times it reads”. Writing the pages reads once; a service may re-read on every call.

Once configuration reaches the handler function, keep one more rule: do not print sensitive items. The example’s Token shows only “whether it is configured” and its length.

var token = string.IsNullOrEmpty(options.Token) ? "Not configured" : $"Configured ({options.Token.Length} characters)";

Its value appears nowhere in the page, the log, or API responses. What the log records are numbers like “Clean up 22 characters, 1 line, at most 24 characters per line”, not the source text and not the password. This is not fussiness. Logs get copied, pasted into chat windows, and folded into issue reports; one casual extra line carries the credentials out with it.

appsettings.json should not hold real credentials either. It is a file that travels with the source, so once committed it is in the history. The example leaves it empty and the real value goes through an environment variable; Chapter 16 used the same approach when connecting to a model service.

The Error popup is another outlet. Its message is displayed as raw HTML; splicing configuration values into it is the same as sending credentials to the page. When you need to report an error, report the key name, not the value.

The whole path configuration takes into the handler function.

Figure 21-5 Configuration is read in the host, services are taken from the container per call, and the handler function only translates

Greeting and AuthMessage take a different path. They are read once while the pages are being written and become text on the page directly. So changing a sentence needs a restart, but what that buys you is “the same page code, a different set of copy when you change hosts”.

21.6 Host Logging Configuration and the Health Check Endpoint

Logging is configured on the host side; Gradio does not set up a separate one. The example’s appsettings.json adjusts only three levels.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Gradio.Net": "Information"
    }
  }
}

Push Microsoft.AspNetCore down to Warning and the request logs disappear. During local debugging that string of “Request starting / Request finished” is noisy; once it is suppressed, what remains is the application’s own words. Gradio.Net stays at Information so you can see it when the queue or routing goes wrong. For finer control, keep adding by category name, for example setting only Gradio.Net.GradioQueue to Debug.

What you can see in the log is the source of several conclusions in this chapter: the startup address, the heartbeat starting and stopping, the character and line counts of each cleanup, and a long task receiving cancellation. None of them contain source text or credentials.

A lower level is not always better. Debug prints request details, including things you do not want to keep; Warning swallows the startup information too, so when something breaks you cannot even see the address. Information is the default level and the one the example uses.

Gradio’s own logs are under the Gradio.Net.* category. When a binding fails, the queue writes a fail: line with the exception and the call stack together. That “Number received an empty string” line during the example’s debugging was seen from here. It is far more useful than the “something went wrong” line on the page, so do not push this category below Warning.

Health checks are another matter; you have to turn them on explicitly.

builder.Services.AddGradioHealthChecks();   // register the checks
app.MapGradioHealth("/health");             // give it a path

Once enabled, GET /health returns 200 and one line of plain text Healthy. It checks two things: that the pages are written and that the queue is up. Both have to hold before it counts as healthy. A host that only listens but has not written its pages, and a host whose queue is not up, should neither be sent traffic.

These two conditions are hard not to satisfy on a local machine, so what you normally see is always Healthy. Its value is in automated environments. An orchestrator probes once during the few hundred milliseconds after the process comes up, and sends no traffic if it is not healthy.

The framework’s response supports three levels, Healthy, Degraded, and Unhealthy; this check returns Healthy only when both conditions hold, otherwise Unhealthy. What it returns is plain text, not JSON. The probe looks only at the status code, not the body. How often to probe and how long before timeout are set by the orchestrator, not the application; local development does not need this endpoint at all, and its reader is the process manager.

This endpoint is opt-in. It is not in Gradio’s route table, and the Python version has no such route either; the framework does not add it by default so that “which paths this application exposes” stays countable. In the standalone host the counterpart is GradioServerOptions.HealthCheckPath; fill in a path and it registers and maps at the same time.

One more: health checks sit outside authentication. In the example, while logged out, /config returns 401 and /health returns 200. This is deliberate. Probes carry no cookie; put the health check behind the gate and the orchestrator will never see healthy. It returns only Healthy or Unhealthy and leaks no page content.

21.7 Lifecycle and Graceful Shutdown

The host’s life and death are broadcast by IHostApplicationLifetime, at three moments: startup complete, stopping, and stopped.

app.Lifetime.ApplicationStarted.Register(() =>
{
    hostFacts.Address = string.Join(" / ", app.Urls);
    hostFacts.StartedAt = DateTimeOffset.Now;
    app.Logger.LogInformation("Workbench started: {Address}", hostFacts.Address);
});

app.Lifetime.ApplicationStopping.Register(() => { /* wind down */ });
app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Host stopped"));

ApplicationStarted is the moment to get the actual address; app.Urls is empty before then. ApplicationStopping is the window for winding down. Connections are still there and background tasks have not stopped; you still have a chance to tell them “it is time to stop”.

Handler functions in the queue are not in this window. When the host stops, Gradio’s queue does not cancel the handler functions that are running for you; the process exits and they disappear with it, and finally is not guaranteed to run. Run it once in the most intuitive way and you can see it. Stop the host while a streaming task at one frame per second reaches frame 2; the task keeps emitting up to frame 7, then the process is gone and there is no winding-down line in the log.

Two things have to be told apart here: the SSE long connection and the run inside the queue. The connection belongs to the host and breaks as soon as the process stops; the run belongs to the queue, and nobody notifies it when the host stops. Losing the former is no loss; losing the latter leaves work half done.

To wind down, you have to prepare a marker yourself and cancel it in ApplicationStopping.

var stopping = new CancellationTokenSource();

app.Lifetime.ApplicationStopping.Register(() =>
{
    app.Logger.LogInformation("Host is stopping: cancelling long tasks, background tasks are winding down, connections close afterwards");
    stopping.Cancel();
});

The handler function uses this marker together with the request’s own cancellation token.

async IAsyncEnumerable<string> LongRun([EnumeratorCancellation] CancellationToken token)
{
    using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, stopping.Token);

    for (var i = 1; i <= 20; i++)
    {
        var cancelled = false;

        try
        {
            await Task.Delay(1000, linked.Token);
        }
        catch (OperationCanceledException)
        {
            cancelled = true;
        }

        if (cancelled)
        {
            app.Logger.LogWarning("Long task cancelled: request cancellation = {Requested}, host stopping = {Stopping}",
                token.IsCancellationRequested, stopping.IsCancellationRequested);
            yield break;
        }

        yield return $"Frame {i}, {DateTimeOffset.Now:HH:mm:ss}";
    }
}

Two cancellation paths merge into one. Close the browser page and the request’s own token cancels; stop the host and stopping cancels. The handler function only knows linked and does not need to know who pressed it.

After the change, run the same scenario again and the log looks like this.

info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
info: Chapter21[0]
      Host is stopping: cancelling long tasks, background tasks are winding down, connections close afterwards
warn: Chapter21[0]
      Long task cancelled: request cancellation = False, host stopping = True
info: Chapter21.Heartbeat[0]
      Heartbeat stopped, 11 times in total
info: Chapter21[0]
      Host stopped

From issuing the stop to the stream ending took 0.01 seconds. request cancellation = False shows that this time the host stopped the process.

The ApplicationStopping callback has to be short. It runs synchronously inside the stopping flow; do long work in it and the whole shutdown is held up by it.

Background tasks do not need you to cancel them. A BackgroundService’s stoppingToken comes from the host, StopAsync is called, and finally runs. The example’s heartbeat writes its total count in finally; that line “Heartbeat stopped, 11 times in total” is the evidence it ran.

The order of await using also matters. GradioServer.DisposeAsync stops the service first and then releases the container, so background tasks get a chance to finish finally; release the container first and the tasks do not even get a chance to wind down.

One more gate, the shutdown grace period. How long the host is willing to wait for running requests is decided by HostOptions.ShutdownTimeout, thirty seconds by default. The example changes it to five seconds.

builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(5));

What it governs is “how long the host is willing to wait”, not “cancel for you”. If a request ignores cancellation, it is cut off anyway when the five seconds are up. So the correct division of labour is: the application cancels by itself, and the grace period is only a fallback.

Cancellation is cooperative. Task.Delay, HttpClient, and stream reads and writes respond to it; pure computation does not. To make a loop cancellable, you have to check token inside the loop, or replace the slow step with a call that responds to cancellation. Chapter 17 covered this rule, and it holds just as well here for host shutdown.

Figure 21-6 The long task: after you click, the frames arrive one by one

The order of stopping.

Figure 21-7 After the stop signal arrives: first cancel, then stop the background tasks, finally release

Ctrl+C and the example’s /stop take the same path, both calling IHostApplicationLifetime.StopApplication(). The only difference is who pressed it. A real application deletes /stop and lets the stop be initiated by Ctrl+C or the process manager.

Finally, be clear about what stays and what disappears. Session state (Chapter 14) is in memory and is gone when the process goes; the upload cache (Chapter 12) is on disk, so the files remain when the process goes, to be collected by the cleanup schedule. The host does not decide these two things, but you need to know them when stopping.

21.8 Chapter Summary

After moving the workbench into an ASP.NET Core host.

  1. Three host shapes: one line of Launch, a configurable GradioServer, and a self-built AddGradio + UseGradio. All three use the same route table, and the page code does not change.
  2. Address and port belong to the host. The standalone host reads GradioServerOptions, the self-built host reads Urls (or --urls at startup). Port 0 lets the system pick, and you read the actual value from BaseAddress or the log.
  3. The mounting order is “write the pages first, then hand them in”. gr.Blocks() opens a rendering scope; the Blocks in the container does not. Write it the other way round and the first button’s event binding reports “does not belong to any application”.
  4. Take services from the container per call. Take only IServiceScopeFactory and open a scope on each call. Scoped is one per call, Singleton is shared across calls; business rules stay in core, which does not reference Gradio.NET.
  5. Configuration comes in from the host, credentials do not go out. IOptionsSnapshot means editing the file needs no restart, and environment variables override the file; sensitive items show only their length, and logs record only numbers.
  6. Winding down is up to you. Handler functions in the queue are not on the host’s shutdown chain; you cancel your own marker in ApplicationStopping; BackgroundService is stopped correctly; ShutdownTimeout is only a fallback.

One more boundary: a host is not a necessity. With only this one UI, for your own use alone, demo.Launch() remains the right choice. This chapter is about “what to do when it needs to live in the same process as something else”, not “every application should build its own host”.

The cost should be spelled out too. There is one more layer of host to maintain, one more configuration file to manage, and one more responsibility: “guard the endpoints you added yourself”. What you get in return is that this workbench can live in the same process as other services, using the same container, the same configuration, and the same logging, instead of an island that can only run on its own.

The amount of code in this chapter is not large; the hard part is ownership. Once you are clear about which things belong to the process and which to the application, the decisions after that fall into place.

When you wire the workbench into your own application, go through it in this order.

  • Is there a line with the actual address in the startup log, matching Urls;
  • Open a page while logged out and confirm it is still the login card; /config is 401, /health is 200;
  • Click a business button once and confirm the service instance changes and the count climbs;
  • Change a value in appsettings.json and click again to confirm the new value takes effect;
  • If you added the host’s own endpoints, confirm whether they need a gate. Gradio’s authentication does not cover them;
  • Click the long task, stop the host, and confirm the log has both the cancellation line and the heartbeat-stopped line, and the process exits cleanly.

The next chapter is the last chapter of the book. Chapter 22 exposes the capabilities behind the UI as callable interfaces.

Chapter 22. API and OpenAPI

The work of the previous twenty-one chapters all lives on one page. The components are laid out, the events bound, the host wired up; a person clicks a button, the handler function runs, and the result comes back into the components. These handler functions must also be able to run without anyone clicking a button.

Every button with a handler function bound to it is also an HTTP endpoint. No extra declaration, no separate controller: once the page is written, the API is already there. What is left to decide is what this API is called, how others know it exists, and which APIs should not be known to others.

Names come from bindings, two documents answer different questions, and calls split into two routes, direct and job-style. At the end of the chapter a client on the same machine walks the whole path, and along the way checks exactly what visibility does and does not control.

First look at what this chapter adds to the workbench. The sample gains one page, “API”, at the address /api.

Figure 22-1 The API page: the “Clean up” button on the left can be called by a script, while the “Streaming” button on the right shows its process only through a job-style call

Every button on the page is one binding, that is, one API. The binding for the “Clean up” button on the left looks like this.

run.Click(ArrangeForApi, [text, width], [body, stats],
    apiName: "API Clean up",
    apiDescription: "Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)");

The only difference from the previous twenty chapters is one more apiDescription. apiName was already used in Chapter 5 and apiVisibility in Chapter 20; this chapter explains those two parameters fully, then adds the two things never mentioned before: the description and the parameter names.

The boundary first, clearly: this chapter is about “how it gets called”. The authentication door still works as in Chapter 20; this chapter mentions it only when it needs to tell “the door” apart from “the curtain”.

22.1 Rules for Deriving API Names

Every binding with a handler function has a name whether you want one or not. If you want one, it is the one you gave; if you do not, the framework generates one for you. There are only four generation rules, and once you know them you can predict what your API will be called.

Figure 22-2 The four sources of a name, and the suffix when names collide

First. If apiName is given, use what was given, as-is, with no processing. Letters and digits are fine, non-ASCII letters are also accepted, spaces are fine, starting with a digit is fine too.

Second. If it is not given but the handler function is a named method, use the method name. Write Click(Handlers.CleanText, …) and the API is called CleanText, matching the C# method name.

Third. If it is not given and the handler function is a lambda or an anonymous method, it is called lambda. The name the compiler generates for such a method is not a valid identifier, so the framework does not guess and writes lambda uniformly. From the second one on, a numeric suffix is added: lambda_1, lambda_2.

Fourth. If there is only front-end script and no handler function, it is called js_fn; if there is neither, it is called unnamed. Both of these are private. With no handler function and no name given by anyone, there is no reason for it to become an API.

You do not need a separate experiment for these four: a pair sits at the bottom of the sample’s “API” page. Neither button is given a name; the left one binds ApiDesk.CharacterSummary, so the API is called CharacterSummary; the right one binds a lambda, so the API is called lambda_1.

Why lambda_1 and not lambda? Because the name lambda is already taken. The “Copy link with state” button on the “Text” page also has an unnamed binding inside it; it got lambda first, and it is itself Undocumented (one of the three undocumented names in 22.3 is it). That is where the suffix comes from. The suffix is not added only for a duplicate name; it is added as soon as the name is taken, and the order in which names are taken is the order in which the page is written.

Local functions keep their names too. Write the handler function as string CharacterSummary(string text) => … directly in Program.cs and the API name is CharacterSummary. The method name the compiler generates for it is <<Main>$>g__CharacterSummary|0_0; the original name is still there between g__ and |, and the framework can read it out. Lambdas and anonymous methods have no such segment, which is why they are all called lambda. So “named method” means whether the way you write it has a name, not that it has to be moved into a class.

The other two derived names are in the sample too. js_fn comes from the purely front-end binding inside that share button, and unnamed and unnamed_1 come from the bindings inside the two cancel buttons on the “Run” page. Neither kind is a handler function you wrote, both are private, and they do not enter the list.

The same /config also shows the distribution: of 120 bindings, 110 are public, 3 are undocumented, and 7 are private. These numbers come up again later. The 110 names in the API list are exactly these 110 public bindings.

Names you give yourself work the same way. Write apiName: "Duplicate" on two bindings and the second one’s API name becomes Duplicate_1. Add two yourself and you will see it. This rule has a direct consequence. Renaming an existing API can quietly change another one. When two names collide, the second gets a suffix, while the caller is still calling by the original name, and the 404 it gets is exactly the same as “name misspelled”. So either name things systematically, or read through the list after every change.

The same name is written differently in two places; this is the easiest one to trip over.

  • In /config, api_name is Clean up, with no leading slash;
  • In /gradio_api/info, the key is /Clean up, with a leading slash;
  • In a URL it is one segment of the path, /gradio_api/call/Clean up.

The leading slash is “the key of this one list”, not a path separator. When the client assembles a URL, do not add another slash: /gradio_api/call//Clean up is a different path and the route will not match.

What characters a name can hold turns out, in testing, to be broader than you would think and narrower than you would think.

  • Letters and digits are fine; non-ASCII letters are also accepted. curl percent-encodes the name and the call works.
  • Spaces are fine, but they must be encoded as %20; unencoded, the request line is invalid.
  • Slashes are not. Write a name as With/Slash and /gradio_api/call/With%2FSlash returns 404, saying “cannot recognize this name”; put the slash into the URL as-is and the route treats it as two segments and returns 405. In other words, a name with a slash cannot be called from the moment it is generated, yet it is still listed in /info.

So the naming rule collapses into one sentence. Use letters and digits; non-ASCII letters are also accepted, slashes are not. For a sense of hierarchy, use a prefix like Text cleanup, not text/Clean up.

One more thing is tied to the name: the name is the object of visibility. Chapter 20 said that Private means “this name is neither shown nor recognized”. With no name, showing or not showing is meaningless, so unnamed is necessarily private. That is a rule hard-coded in the framework. Conversely, as soon as you give a name, it is public by default, even if the binding is only an intermediate step on the page. The default chooses “public” over “private” because the authors of most bindings never thought about APIs at all; that default is friendly to teaching and unfriendly to security, so the Chapter 20 advice to “set intermediate steps to Private” is not fussiness.

22.2 API Descriptions and Parameter Names

The name settles “what it is called”; next is “how to use it”. After a caller gets a name, it needs to know two things: what this API does, and what each of those parameters is.

The sample’s binding is this line.

run.Click(ArrangeForApi, [text, width], [body, stats],
    apiName: "API Clean up",
    apiDescription: "Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)");

apiDescription is the API’s own description. It appears in the description field of /gradio_api/info and also becomes the summary of that operation in OpenAPI.

The binding has one more parameter of the same kind, endpointDescription. The name is very similar, but the effect is smaller than it looks. Try two sets of temporary bindings, one each way. Write only apiDescription and OpenAPI’s summary is that description; write only endpointDescription and the summary is it too; write both and only apiDescription appears, with not a single character of endpointDescription showing. So it is a substitute that steps in when apiDescription is not written. It neither stacks nor overrides. The sample does not write it, because there is no reason to write the same thing twice.

OpenAPI’s description is longer than the summary because the framework appends a stretch of automatically generated English after it.

Wrap the source text by width and return the body and statistics (param_0 is the source text, param_1 is the characters per line)
Output must be fetched from GET /gradio_api/call/API Clean up/{event_id}.
Returns an array of 1 elements of the following format: ["output ({'type': 'string'})"]

The first line is yours; the second and third are what it added. The added part explains two things: that the result has to be fetched with a separate request, and how many elements the returned array has and what type each is. The description of that GET operation also says “the final event is event: complete”, and the last thing written into the stream is exactly it, with the complete output array in data (22.5 looks at the whole stream). Write the client following that sentence; there is no need to guess which events this stream has.

Parameter names are another thing that goes against intuition. They are not called text and width; they are called param_0 and param_1.

C# method parameters have names, but the API’s parameter names do not come from there. In /info, each parameter looks like this.

{
  "label": "Source text",
  "parameter_name": "param_0",
  "parameter_has_default": true,
  "parameter_default": "Wrapping looks simple,",
  "type": { "type": "string" },
  "component": "Textbox"
}

label is the component’s label, parameter_name is the positional name, and parameter_default is the component’s value at this moment. The three fields each say their own thing, but they are easily misread as one meaning. parameter_has_default says “this component currently has a value”. As soon as something is filled into the component, it is true. The real default-value semantics is the one from Chapter 3: a parameter that is not supplied gets the type’s default value.

Two requests make this clear. Send an empty array to API Clean up, then read the result stream by the event_id you get back.

POST /gradio_api/call/API Clean up   {"data": []}
GET  /gradio_api/call/API Clean up/{event_id}
→ event: complete
  data: ["/", "0 lines, 0 characters, longest line 0 characters"]

Neither parameter is supplied; the first gets an empty string, the second gets null, the handler function runs anyway, and the result is "/", from the interpolated $"{t}/{w}". Supplying one extra is fine too: the 9 in {"data":["a",3,9]} is dropped and the result is still "a/3". These two behaviors match the component contract from Chapter 3 exactly, just through a different entry point.

Since parameter names are positional names, the description has to spell out the order. The sample’s description deliberately writes “param_0 is the source text, param_1 is the characters per line”, because someone reading the document sees only param_0. This is not empty courtesy. For an API with only param_0, that sentence is the one thing the caller can rely on.

The same holds on the return side: returns has only label, type, and component, no name. Two return values are two positions in the array, with the order set by outputs. So the phrase “return the body and statistics” is something you have to write into the description yourself.

22.3 API Info and the OpenAPI Description

The name and the description both live on the binding; next you read them out. There are two addresses, both behind authentication, both read-only.

Figure 22-3 The two documents answer two questions: what names there are, and how to send a request

The first is GET /gradio_api/info. Its top level has only two keys, named_endpoints and unnamed_endpoints. The former is a mapping from names to descriptions, the latter is basically empty. Because every binding gets a name, even unnamed is a name. So the only one you can actually read is the first.

In the sample app it has 110 names and the whole JSON is around 450 KB. The bulk is the four ready-made call snippets under each name: Python, JavaScript, bash, CLI. The bash one is the most useful; it gives you a command you can paste straight into a terminal.

curl -X POST http://127.0.0.1:7860/gradio_api/run/API Clean up -s -H "Content-Type: application/json" \
  -d '{"data": ["Wrapping looks simple...", 12]}'

Note that it uses /gradio_api/run/, the direct-call route (22.4). The list itself does not say what distinguishes this route from the job-style one; you have to know that yourself.

The values in data are the component’s current values, not “example values”. The sample’s text box holds a whole paragraph, and the snippet carries that paragraph along verbatim. So it is a starting point for copying, not a finished product you can run as-is. Replace the first parameter before pasting.

/info supports one query parameter, ?all_endpoints=true. With it, Undocumented names are listed too; without it, only Public. In the sample the default is 110, and with the parameter 113; the three in between are the bindings marked Undocumented. Private does not appear in either case.

The second is GET /gradio_api/openapi.json, a standard OpenAPI 3.0.2 document. Its info section comes from the app itself.

{
  "title": "Personal Local Workbench",
  "description": "The public API of the Personal Local Workbench: one cleanup, one streaming, and three visibility levels.",
  "version": "xxx"
}

The title is the one from gr.Blocks(title: …); the description is demo.Description. That property exists for OpenAPI, so /info does not have it; the version on the last line comes from the upstream protocol, not the one in PackageReference.

The paths section is the important part: each name takes three paths.

/gradio_api/call/API Clean up          POST   submit, returns event_id
/gradio_api/call/v2/API Clean up       POST   another path for the same call
/gradio_api/call/API Clean up/{event_id}  GET  fetch the result by number, SSE

The sample has 110 names and 331 paths. 110 times 3 plus one upload matches exactly. operationId is the name, and the GET one is “the name plus _get”; summary is apiDescription; and the property names of requestBody are param_0, param_1.

Two omissions matter, because they mislead people writing code against the document.

First, OpenAPI has no /gradio_api/run/{name}. Direct calls really do work, and the bash snippet in /info uses exactly that, but it is not in OpenAPI. The document describes only the job-style route.

Second, OpenAPI has no security scheme. The sample has authentication on; an unauthenticated request to /gradio_api/openapi.json returns 401, yet the document you get after logging in has no securitySchemes anywhere. Only the /gradio_api/upload path says security: [{"login_check": []}], and the login_check scheme is not defined at all. In other words, the document cannot be used to decide “does this API require login”. To decide that, look at whether it is behind the door. What Chapter 20 said still holds here.

Both documents can be read once on the page. The sample’s “API” page has two buttons, and they read exactly this same data.

string ReadInfo()
{
    var named = demo.GetApiInfo("/", "/", false)["named_endpoints"]!.AsObject();
    // ...one line per name: name, visibility, parameter count, description
}

string ReadOpenApi()
{
    var document = demo.GetOpenApiDocument("/");
    var paths = document["paths"]!.AsObject();
    // ...count paths, count names
}

Blocks.GetApiInfo and Blocks.GetOpenApiDocument are what happens behind those two HTTP addresses. Reading them on the page has one benefit: you can see at once that “the document is a mirror of the bindings”. Change one binding, refresh the list, and it changes. Both buttons are themselves private, because “reading the document” should not turn into yet another API.

Figure 22-4 The list is a mirror of the bindings: 110 names, each with visibility, parameter count, and description

The two documents can divide the work: use /info to find names, count parameters, and copy snippets; use OpenAPI to generate clients and plug into code tools. The former is for people to read, the latter for machines. Using them the other way round feels awkward. OpenAPI has no “take it all in at a glance” name list, and /info has no structural definition of the request body.

A 450 KB JSON is not something to read with your eyes. When you only want the names, filter it.

curl -s -b cookies.txt http://127.0.0.1:7860/gradio_api/info \
  | jq -r '.named_endpoints | to_entries[] | "\(.key)\t\(.value.api_visibility)\t\(.value.parameters | length)"'

One name per line, followed by visibility and parameter count. The code_snippets section takes up the most space; filter it out and the whole document is only a few kilobytes, much easier to read. This is a habit worth building. Once there are many APIs, “is this name actually there” is a question you ask every day, and answering it by flipping through the page is too slow.

22.4 Direct Calls and Job-Style Calls

The same handler function has two call paths with the same parameters; the difference is “who waits for you”.

Figure 22-5 Two routes: one connection waits for the run to finish, the other submits a job and takes a number

A direct call is one request.

POST /gradio_api/run/API Clean up
{"data": ["Wrapping text...", 12]}

→ 200
{"data": ["Wrapping loo\n...", "12 lines, 109 characters, longest line 12 characters"],
 "is_generating": false, "duration": 0.0065, …}

The request goes out, the connection hangs there, the handler function finishes, and the body is the result. No number, no intermediate state, and nowhere else to check how this run went.

A job-style call is two requests.

POST /gradio_api/call/API Clean up
{"data": ["Wrapping text...", 12]}

→ 200 {"event_id": "0367afaa297045b58a4506f35a1e2b5f"}

Once you have the number, send a separate GET /gradio_api/call/API Clean up/0367afaa…; the server treats this connection as a stream and writes it down frame by frame until the run ends. The number identifies this run and has nothing to do with the page. When the same handler function is clicked once on the page, it goes through this same queue too, only the number is not shown to you.

There are four differences, each one tested for real.

One: direct calls do not go through the queue. The three “A1”, “A2”, “A3” buttons on the sample’s “Run” page have a concurrency limit of 1, and after every run they log a line “how many were running on entry”. Send two /run at the same time: A1 enters at 21:38:48.182, A2 at 21:38:48.598, and the second one’s record says “2 running on entry, peak 2”. The limit did not stop it. Switch to two /call: A1 enters at 00.854 and leaves at 02.847, A2 only enters at 02.921, and both say “1 running on entry”. So the concurrency limit, queue limit, and queue rejection from Chapter 15 have no effect at all on /run.

Two: for a streaming handler function, a direct call delivers only the first frame. For the same streaming API, the body /run returns has is_generating set to true and data holding the first frame, and then the connection closes. Where do the remaining frames go? Nowhere; they are dropped. To see the process you can only use a job-style call.

Three: a job-style call sends you the process frame by frame. The result stream writes intermediate values out one frame at a time and closes with an event: complete; /run has only the body after the run finishes. Messages like queue position, run starting, and progress are on the /queue/data the page reads, not in the result stream — the result stream delivers only outputs.

Four: failures look different. /run fails with a 500 and a body of {"error": …}; the submit step of /call still returns 200, and the failure shows up in the result stream as an event: error plus a data (see 22.5 for details).

/call/v2/name exists too: the submit and retrieve formats are identical to v1, run both once and there is no difference in the frames returned. The document lists both, and in practice either works; this book’s sample uses v1 because it matches what the /info snippet writes.

Which to choose depends on whether this call needs the process.

  • Only need the result and it runs fast? /run. One line of curl, the least work in a script.
  • Need the process, or it may run a long time? /call. One more request buys you a stream you can read.
  • A streaming handler function can only use /call; /run gives you just the first frame.

One more, less obvious. /run “not going through the queue” also means it is not managed by cancellation. The cancel button in Chapter 17 cancels runs in the queue; /run is not in the queue, so it cannot be cancelled. With one person on a local machine this is no problem; when a script calls in bulk, a runaway /run can only be waited out until it ends on its own.

22.5 Consuming Streaming Results

The stream a job-style call gets is the one that most needs explaining. It is named SSE events, a different kind of frame from the queue stream the page reads.

First look at a real stream. The sample’s streaming API sends the wrapped body out line by line, eight lines, three hundred and fifty milliseconds apart.

event: generating
data: ["Wrapping loo"]

event: generating
data: [[["append",[],"\nks simple,"]]]

event: complete
data: ["Wrapping text...\nSkip all bla"]

The first thing to remember: the event name is on the event: line, and data holds only outputs. The description of the GET operation in OpenAPI says “the final event is event: complete”, and the last thing written into the stream is exactly it. Read it by the SSE standard. One event: line says what this frame is, one data: line gives the content, with a blank line separating them.

A stream that finishes normally has only three kinds of events, each in its own place.

  • generating, an intermediate frame; data is the output array for that frame.
  • complete. The run is done; data is the complete output array, and then the connection ends.
  • heartbeat. Inserted when the connection has been idle long enough; data is null and does not mean there is a result.

When the run fails, or the number cannot be read, it is event: error, with the reason in data. Queue messages like queue position, run starting, progress, logs, and close_stream are not written into this stream. They belong to the /queue/data the page reads; what a job-style call gets is output that has already been picked clean.

The second thing, and the easiest to trip over: an intermediate frame is not necessarily a complete value.

The first frame is complete. The first element of the data array is “Wrapping loo”. Starting with the second frame, the first element of data holds a patch.

[[["append", [], "\nks simple,"]]]

Take it apart layer by layer. The outermost is an array whose length equals the number of output components; this layer holds patch operations; each operation has three elements: operation name, path, value. There are only two operation names, append to append and replace to replace. The paths are all empty arrays, because patches work on the whole value, not on fields.

The last complete frame goes back to a complete value, and it matches the result assembled from the last generating frame. So there are two ways to consume it, each with its own cost.

Only want the final result. Stop at complete and ignore every earlier frame. Simple, but then you cannot see the process.

Want to show the process. You have to maintain a “value so far” yourself: assign the first frame directly, then stack each patch onto it in every later frame. The sample’s client does exactly this, and its log looks like this.

Frame 1 full (generating) 12 characters, tail "Wrapping loo"
Frame 2 patch append "⏎ks simple," -> total 23 characters
Frame 3 patch append "⏎but first se" -> total 36 characters
...
Frame 8 patch append "⏎Skip all bla" -> total 98 characters
Frame 9 full (complete) 98 characters, tail "…⏎Skip all bla"

The accumulated numbers are computed by the client itself; the server only sends changes. This design is friendly to bandwidth and unfriendly to the client. The “each frame delivers everything up to now” from Chapter 16 is the semantics on the handler function side; before sending to the client, the server compresses it into a diff again. Do not mix the two up.

There are only two kinds of patch, append and replace. Any change can be written as “replace the whole value”, only then no bandwidth is saved. When you hit an operation name you do not recognize, the safest move is to fall back to the complete value in the last frame. complete always gives the complete result; it will not lie to you.

One more boundary, more important than it looks: a stream has only one reader. The first GET claims it; read the same number again and you get a 200 plus one event: error frame.

event: error
data: "404: Not Found"

Note the status code is 200. The error hides in the stream, not in the HTTP status. This is the most easily overlooked rule when reading this stream. A successful GET request does not mean the run succeeded; success or failure depends on the event name — complete is success, error is failure. When the number cannot be read, data is a reason (such as "404: Not Found"); when the run fails, data is an output object describing the failure.

The consequence of the single-reader limit is practical: a dropped connection cannot be recovered by reconnecting. Once the connection breaks, no one picks up the remaining frames of this run, and a fresh GET gets only that 404 frame. When writing the client, put the stream read somewhere it will not be interrupted. Read it through in one go; if you really need to start over, you can only submit again, which means running the handler function once more. Long tasks especially need watching. Better to set a long timeout than to count on reconnecting after a break.

22.6 Calling from a Client on the Same Machine

The previous sections were all curl, enough to see the protocol but not enough to write into a program. This section writes the whole path as a client: log in, read the documents, make both kinds of call, and separate the errors. It runs outside the same process, uses HttpClient, and does not reference Gradio.NET. The API’s contract is those two HTTP documents, not some set of types.

public sealed class ApiClient : IDisposable
{
    private readonly HttpClient _http;
    private readonly HttpClient _stream;

    public ApiClient(string baseAddress)
    {
        var cookies = new CookieContainer();
        var handler = new HttpClientHandler
        {
            CookieContainer = cookies,
            UseCookies = true,
        };

        // Normal requests: thirty seconds is the upper limit. Both clients share the same handler, so the cookies are the same.
        _http = new HttpClient(handler, disposeHandler: false)
        {
            BaseAddress = new Uri(baseAddress),
            Timeout = TimeSpan.FromSeconds(30),
        };

        // Reading streams: no timeout is set. The timeout is decided by the token from the caller, otherwise a long stream would be cut off by the client itself.
        _stream = new HttpClient(handler, disposeHandler: false)
        {
            BaseAddress = new Uri(baseAddress),
            Timeout = Timeout.InfiniteTimeSpan,
        };
    }

CookieContainer hangs off HttpClientHandler, not off HttpClient. So you go through a handler, and the two clients share it. Splitting into two clients is for one thing only. HttpClient.Timeout governs the whole request, including the stream-reading part, so a thirty-second timeout would cut off a long stream, and by the single-reader rule in 22.5, once cut off it cannot be reconnected. The stream-reading client sets no timeout; when to give up is decided by CancellationToken.

CookieContainer is required. Authentication relies on cookies; Chapter 20 said the browser holds two cookies after login, and the client has to save them itself or the second request returns 401.

Login is form-encoded, not JSON.

public async Task<int> LoginAsync(string user, string password)
{
    using var body = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["username"] = user,
        ["password"] = password,
    });

    using var response = await _http.PostAsync("login", body);
    return (int)response.StatusCode;
}

Submitting this step as JSON returns 422. The authentication layer only accepts form data. This is not a big deal, but almost everyone hits it the first time they write a client, because every other API is JSON.

The two steps of a job-style call are, in the client, two methods, “submit” and “read stream”. The read-stream one is the only place in the whole stretch of code that needs care.

public sealed record StreamFrame(string Event, JsonNode? Data);

public async IAsyncEnumerable<StreamFrame> StreamAsync(
    string name,
    string eventId,
    [EnumeratorCancellation] CancellationToken token = default)
{
    var url = $"gradio_api/call/{Uri.EscapeDataString(name)}/{eventId}";
    using var request = new HttpRequestMessage(HttpMethod.Get, url);
    using var response = await _stream.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);

    if (!response.IsSuccessStatusCode)
    {
        yield return new StreamFrame("http_error", JsonValue.Create((int)response.StatusCode));
        yield break;
    }

    await using var stream = await response.Content.ReadAsStreamAsync(token);
    using var reader = new StreamReader(stream);

    // Reading null means the stream is over. Do not use EndOfStream: it waits synchronously for one read, which is exactly what blocks streaming.
    string? pendingEvent = null;
    while (await reader.ReadLineAsync(token) is { } line)
    {
        if (line.StartsWith("event: ", StringComparison.Ordinal))
        {
            pendingEvent = line["event: ".Length..].Trim();
        }
        else if (line.StartsWith("data: ", StringComparison.Ordinal))
        {
            pendingEvent ??= "message";
            yield return new StreamFrame(pendingEvent, JsonNode.Parse(line["data: ".Length..]));
            pendingEvent = null;
        }
    }
}

Three details decide whether this is usable. [EnumeratorCancellation] makes that token actually get into the iterator. The long task in Chapter 21 uses the same pattern; without the attribute, the token passed in and the iterator’s own token are not the same one. HttpCompletionOption.ResponseHeadersRead makes SendAsync return as soon as the response headers arrive, without waiting for the body to end. Without this parameter, SendAsync waits until the stream closes, which is the same as degrading streaming into a one-shot. Reading line by line and pairing the event: line with the data: line is because the blank line is the frame separator and one event is made of those two lines. Read the type first, then the output; the other lines carry no information. The while (await reader.ReadLineAsync(token) is { } line) pattern is not a matter of style either. StreamReader.EndOfStream waits synchronously for one read, and inside an async loop that is exactly what blocks streaming.

The name needs Uri.EscapeDataString. Leave a name with spaces or non-ASCII letters unencoded and Kestrel returns 400 before routing, with an empty body. The reason is that the request line itself is invalid, nothing to do with authentication.

Stacking the patches is these few lines in the client.

static JsonNode? Patch(JsonNode? current, JsonArray patch)
{
    foreach (var node in patch)
    {
        var op = node!.AsArray();
        var kind = op[0]!.GetValue<string>();
        var value = op[2]?.DeepClone();

        current = kind switch
        {
            "append" => JsonValue.Create((current?.GetValue<string>() ?? "") + value?.GetValue<string>()),
            _ => value,
        };
    }

    return current;
}

The _ => value branch catches replace and every operation name never seen before. Written this way it means: recognize append and you save one assignment; do not recognize it and you replace the whole value. The worst case degrades into “every frame is a complete value”, and it cannot compute wrong.

One run looks like this.

dotnet run --project samples-en\chapter22\client -- --base http://127.0.0.1:7860
== 1 Login
200 alice

== 2 API list
110 names by default, 113 with ?all_endpoints=true
  /API Clean up          public        in the default list
  /API Stream          public        in the default list
  /API Undocumented         undocumented  only in all_endpoints
  /API Intermediate Step        -             in neither list

== 3 Direct call
POST /gradio_api/run/API Clean up -> 200
  Body 12 lines, first line "Wrapping loo"
  Statistics 12 lines, 109 characters, longest line 12 characters

== 4 Job-style call
POST /gradio_api/call/API Clean up -> 200 {"event_id":"0367afaa297045b58a4506f35a1e2b5f"}
  event: complete
  data: ["Wrapping loo\n...", "12 lines, 109 characters, longest line 12 characters"]

The results of section 3 and section 4 are identical, and that is no coincidence. Both routes go through the same handler function, the same parameter list, and the same post-processing. The result an API returns must match the result of one click on the UI; that is the premise of a trustworthy API. If they differ, the problem is in parameter translation, not in the two routes.

The next five sections are covered separately. Section 5 is streaming, whose output 22.5 has already looked at; sections 6 through 9 are visibility, the four kinds of failure, and OpenAPI, described below in order.

The four lines in section 2 are a small summary of this chapter. In the same app, two public, one undocumented, one private — the names are all there, but whether they can be called is not the same.

Four Kinds of Errors

The client splits them into four kinds, two in section 6 and two in section 8. All four look different and are handled differently.

First kind: not logged in, 401. That is the first line of section 8. Take a client that has never logged in and ask it for the list.

Ask for the list without logging in -> 401 Not authenticated

The body also carries auth_message, the sentence from Chapter 20. All the client can do is log in again; retrying is pointless.

Second kind: the name does not exist, 404. Both lines in section 6 are this one; /call and /run give the same answer.

{"detail":"Could not infer function index for API name: API Intermediate Step"}

“Cannot recognize this name”. Not “you have no permission”. A private API and a misspelled name give the same answer, and that is deliberate. Someone probing names cannot find out which name is real. Faced with a 404, the client has only two options: change the name, or do not call it.

Third kind: the handler function says no, 500 plus a sentence in plain words. The sample’s cleanup API throws Error when the width is less than 2.

if (width is < 2)
{
    throw new Error("Width must be at least 2 characters.");
}

What the client receives is this.

{"error":"Width must be at least 2 characters.","duration":10,"visible":true,"title":"Error"}

Error is “the app says no”, not “the program collapsed”, so this sentence is bound to appear in the receipt the caller reads, regardless of the ShowError switch. Chapter 17 used it for validation; here it is the API’s error contract. For a business rejection you can state in one sentence, use Error and let the caller read your exact words.

Fourth kind: the parameter type is wrong, 500 plus a sentence in English. Pass the width as a string.

{"error":"A number field's value is a number; the client sent '\"twelve\"'. (Parameter 'value')"}

This sentence is thrown by the framework during preprocessing; it is not your words, and it is in English. Reading it, the caller can only tell that it sent the wrong type; for what to send instead it has to go back to the document. That is why the parameter order has to be written into the description.

Crashes and business rejections must be kept apart. When the handler function throws an unwrapped exception, by default the client sees only {"error":null}, and the reason is only in the server’s log. This is the switch.

demo.ShowError = false;   // Default: a crash only says "An error occurred", details go to the log
demo.ShowError = true;    // For local single-user use: the crash reason also goes into the receipt

The sample turns on the latter. With it on, the English “wrong parameter type” sentence above appears in the receipt; turn it off and the same request returns only {"error":null}, and you have to go to the console for the reason. A real crash (throwing an unwrapped exception) is the same: with it on, it returns {"error":"Internal error","visible":true}; with it off, null.

This switch governs crashes only, not Error; the latter is always visible. For your own use on a local machine, turning it on saves trouble; the day you let others connect, turn it off, because exception messages often contain paths, SQL, and internal structure, and those things should not show up on someone else’s terminal.

One more distinction that echoes Chapter 17. Login failure and run failure are not in the same place. The former is a 400 plus one fixed sentence; the latter is a 500 plus error. The former happens before you get the page; the latter happens in the queue. When writing the client, do not expect to handle both in one branch.

22.7 API Visibility

Chapter 20 gave the definitions of the three visibility levels and said a private API returns 404. This section checks it again with the client, because “not in the document” and “cannot be called” are two different things that are often treated as one.

The actual effect of the three levels, tried one by one with the same client.

BindingDefault listall_endpointsOpenAPICall by name
PublicInInIn200
UndocumentedNot inInNot in200
PrivateNot inNot inNot in404

The Undocumented row is the point of this section. It only stays out of the default list; it is not uncallable. With ?all_endpoints=true it is listed all the same; call it by name and it returns an event_id all the same. So it stops no one who wants to call it. What it stops is “seeing it while flipping through the document”.

Private is the one that really blocks. It enters neither document, calling it by name returns 404, and the /run route is 404 too. In the sample, API Intermediate Step is this level. The button on the page can still be clicked as usual, but any script calling it fails.

Chapter 20 already gave the answer on how to choose among the three; here is just one line more. Undocumented is not a security measure; it stops “seeing it while flipping through the document”, not “someone wanting to call”. To block, only Private works.

One more that is easy to forget: visibility only matters when there is a name. A binding with neither a handler function nor a name is private no matter what you pass to apiVisibility. That rule is hard-coded in Blocks, not a configuration option.

One more, on the time dimension. Renaming is a breaking change. The name is the caller’s only anchor; rename a public API and every script that calls it stops working on the same day. It raises no error, only returns a 404 — the same as “name misspelled”. Count the cost of a rename in advance. Either keep a binding under the old name and add one under the new name, with both existing together for a while; or accept one break and then notify people one by one. Changing a description is free, change it whenever; changing the parameter order is not, and is just as breaking as a rename. Give param_0 a new meaning and the caller gets no warning at all; it simply goes on treating the new meaning as the old one.

Confirm once more the order when authentication and visibility stack up: door first, then curtain. An unauthenticated request to /gradio_api/info returns 401; you cannot even ask “what names are there”. Only after login does visibility get to say “is this name shown”. The reason the client’s section 2 can see 110 names is that section 1 logged in successfully. Without section 1, every later section is a 401.

22.8 Chapter Summary

This chapter turned the capabilities behind the UI into callable APIs.

  1. Names come from bindings: given apiName uses what was given; without it, derive from the handler function (method name, lambda, js_fn, unnamed); collisions add a numeric suffix, both given and derived. Do not put slashes in a name, and percent-encode names with spaces or non-ASCII letters.
  2. Write the description in apiDescription. It goes into /info’s description and OpenAPI’s summary; endpointDescription is only its substitute, and when both are written the former wins. Parameter names are positional names like param_0, so the order must be written into the description.
  3. The two documents divide the work. /info answers “what names are there, how many parameters”; OpenAPI answers “how to send a request”. The former is for people, the latter for machines; OpenAPI has no /run and no security scheme, so do not use it to judge whether login is required.
  4. Two call routes: /run asks once all the way through, skips the queue, and gives only the first frame for streaming; /call submits a job and takes a number, goes through the queue, and gives streaming frame by frame. If you need the process, you can only take the latter.
  5. Streaming frames are named events: the event: line gives the type and data: holds only outputs; the types are generating/complete/error/heartbeat. The first frame is complete, intermediate frames are append/replace patches, and the last complete frame is complete again. To only get the result, wait for complete; to get the process, stack the patches yourself.
  6. Errors come in four kinds: 401 means log in again, 404 means change the name, 500 plus error is a business rejection (Error is always visible), and a wrong parameter type is the framework’s English. A crash by default only says “An error occurred”; only with ShowError on does it give the reason.
  7. Visibility is a curtain, not a wall. Private really blocks (404); Undocumented only stays out of the default list (?all_endpoints=true sees it, calling by name works). The UI is not governed by it.

The costs need stating too. There is one more contract to maintain (rename it and callers break, write the description vaguely and callers have to guess; one more boundary to guard), default-public means you have to actively remember which ones should be private; and there is one more difference you cannot see in the documents. /run and /call behave differently with the queue, and OpenAPI will not tell you that difference.

What you get in exchange is that the workbench’s capabilities no longer belong only to that page. A script, a scheduled task, another program — all can use the same logic and the same results, and the results they see are the same as the ones you see when you click a button.

Before you open the APIs to others, go through this sequence.

  • Open /gradio_api/info, count the names, and confirm nothing that should be hidden is left exposed;
  • For every name you want public, confirm it has an apiDescription and that the description spells out the parameter order;
  • Call once with /run and compare the result with one click on the page;
  • Call a streaming API once with /call and confirm you can read both intermediate frames and the completion frame;
  • Call a private name once and confirm it is 404, not 200;
  • Call /gradio_api/info once without logging in and confirm it is 401;
  • Send a parameter of the wrong type and confirm the caller reads enough to fix it itself.

References

Gradio.NET

  • NuGet package page https://www.nuget.org/packages/Gradio.Net — package versions, target frameworks, dependencies and release history. The version pinned throughout the book is 0.6.30.8.
  • Source repository https://github.com/feiyun0112/Gradio.Net — quick start, the two styles of writing (gr factories and core types), and ten official demos (Interface, Blocks, Chat, Streaming, Form, Files, Media, Multipage, Themes, Charts).
  • API documentation inside the package, installed at %USERPROFILE%\.nuget\packages\gradio.net\0.6.30.8\lib\net10.0\Gradio.Net.xml. It is authoritative for the types, parameters and default values of public members; the book only describes the parts that can be reproduced with the samples.
  • Upstream Gradio documentation https://www.gradio.app/docs — the source of component and parameter names. Gradio.NET is a .NET port of Gradio 6.30.0 and shares its front end and protocol; the book does not assume you have read this documentation.

.NET and ASP.NET Core

OpenAI-Compatible Interfaces